first commit
This commit is contained in:
6
comm/Kernel/config/struts2/api.xml
Executable file
6
comm/Kernel/config/struts2/api.xml
Executable file
@@ -0,0 +1,6 @@
|
||||
<action name="tokenJsonAction"
|
||||
class="web.TokenJsonAction">
|
||||
<result name="json" type="json">
|
||||
<param name="root">result</param>
|
||||
</result>
|
||||
</action>
|
||||
18
comm/Kernel/show_img.jsp
Executable file
18
comm/Kernel/show_img.jsp
Executable file
@@ -0,0 +1,18 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<%@ include file="include/pagetop.jsp"%>
|
||||
<!-- ========== Css Files ========== -->
|
||||
<link href="css/root.css" rel="stylesheet">
|
||||
<style type="text/css">
|
||||
body{background: #F5F5F5;}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="error-pages">
|
||||
|
||||
<img src="<%=basePath%>normal/showimg.action?imagePath=<s:property value="imagePath" />" >
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
388
comm/Kernel/src/com/alibaba/dubbo/remoting/transport/AbstractClient.java
Executable file
388
comm/Kernel/src/com/alibaba/dubbo/remoting/transport/AbstractClient.java
Executable file
@@ -0,0 +1,388 @@
|
||||
|
||||
package com.alibaba.dubbo.remoting.transport;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.ScheduledThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import com.alibaba.dubbo.common.Constants;
|
||||
import com.alibaba.dubbo.common.URL;
|
||||
import com.alibaba.dubbo.common.Version;
|
||||
import com.alibaba.dubbo.common.extension.ExtensionLoader;
|
||||
import com.alibaba.dubbo.common.logger.Logger;
|
||||
import com.alibaba.dubbo.common.logger.LoggerFactory;
|
||||
import com.alibaba.dubbo.common.store.DataStore;
|
||||
import com.alibaba.dubbo.common.utils.ExecutorUtil;
|
||||
import com.alibaba.dubbo.common.utils.NamedThreadFactory;
|
||||
import com.alibaba.dubbo.common.utils.NetUtils;
|
||||
import com.alibaba.dubbo.remoting.Channel;
|
||||
import com.alibaba.dubbo.remoting.ChannelHandler;
|
||||
import com.alibaba.dubbo.remoting.Client;
|
||||
import com.alibaba.dubbo.remoting.RemotingException;
|
||||
import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers;
|
||||
|
||||
|
||||
public abstract class AbstractClient extends AbstractEndpoint implements Client {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(AbstractClient.class);
|
||||
|
||||
protected static final String CLIENT_THREAD_POOL_NAME ="DubboClientHandler";
|
||||
|
||||
private static final AtomicInteger CLIENT_THREAD_POOL_ID = new AtomicInteger();
|
||||
|
||||
private final Lock connectLock = new ReentrantLock();
|
||||
|
||||
private static final ScheduledThreadPoolExecutor reconnectExecutorService = new ScheduledThreadPoolExecutor(2, new NamedThreadFactory("DubboClientReconnectTimer", true));
|
||||
|
||||
private volatile ScheduledFuture<?> reconnectExecutorFuture = null;
|
||||
|
||||
protected volatile ExecutorService executor;
|
||||
|
||||
private final boolean send_reconnect ;
|
||||
|
||||
private final AtomicInteger reconnect_count = new AtomicInteger(0);
|
||||
|
||||
//重连的error日志是否已经被调用过.
|
||||
private final AtomicBoolean reconnect_error_log_flag = new AtomicBoolean(false) ;
|
||||
|
||||
//重连warning的间隔.(waring多少次之后,warning一次) //for test
|
||||
private final int reconnect_warning_period ;
|
||||
|
||||
//the last successed connected time
|
||||
private long lastConnectedTime = System.currentTimeMillis();
|
||||
|
||||
private final long shutdown_timeout ;
|
||||
|
||||
|
||||
public AbstractClient(URL url, ChannelHandler handler) throws RemotingException {
|
||||
super(url, handler);
|
||||
|
||||
send_reconnect = url.getParameter(Constants.SEND_RECONNECT_KEY, false);
|
||||
|
||||
shutdown_timeout = url.getParameter(Constants.SHUTDOWN_TIMEOUT_KEY, Constants.DEFAULT_SHUTDOWN_TIMEOUT);
|
||||
|
||||
//默认重连间隔2s,1800表示1小时warning一次.
|
||||
reconnect_warning_period = url.getParameter("reconnect.waring.period", 1800);
|
||||
|
||||
try {
|
||||
doOpen();
|
||||
} catch (Throwable t) {
|
||||
close();
|
||||
throw new RemotingException(url.toInetSocketAddress(), null,
|
||||
"Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress()
|
||||
+ " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t);
|
||||
}
|
||||
try {
|
||||
// connect.
|
||||
connect();
|
||||
if (logger.isInfoEnabled()) {
|
||||
logger.info("Start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress());
|
||||
}
|
||||
} catch (RemotingException t) {
|
||||
if (url.getParameter(Constants.CHECK_KEY, true)) {
|
||||
close();
|
||||
throw t;
|
||||
} else {
|
||||
// update by liq 20140314 这里可能是因为服务端还没启动好,而暂时的连接不上,不需要将异常堆栈打印出来,
|
||||
// 因为 dubbo的自动重连机制 会接手处理
|
||||
//logger.error("Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress()
|
||||
// + " connect to the server " + getRemoteAddress() + " (check == false, ignore and retry later!), cause: " + t.getMessage(), t);
|
||||
logger.warn("Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress()
|
||||
+ " connect to the server " + getRemoteAddress() + " (check == false, ignore and retry later!), cause: " + t.getMessage());
|
||||
}
|
||||
} catch (Throwable t){
|
||||
close();
|
||||
throw new RemotingException(url.toInetSocketAddress(), null,
|
||||
"Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress()
|
||||
+ " connect to the server " + getRemoteAddress() + ", cause: " + t.getMessage(), t);
|
||||
}
|
||||
|
||||
executor = (ExecutorService) ExtensionLoader.getExtensionLoader(DataStore.class)
|
||||
.getDefaultExtension().get(Constants.CONSUMER_SIDE, Integer.toString(url.getPort()));
|
||||
ExtensionLoader.getExtensionLoader(DataStore.class)
|
||||
.getDefaultExtension().remove(Constants.CONSUMER_SIDE, Integer.toString(url.getPort()));
|
||||
}
|
||||
|
||||
protected static ChannelHandler wrapChannelHandler(URL url, ChannelHandler handler){
|
||||
url = ExecutorUtil.setThreadName(url, CLIENT_THREAD_POOL_NAME);
|
||||
url = url.addParameterIfAbsent(Constants.THREADPOOL_KEY, Constants.DEFAULT_CLIENT_THREADPOOL);
|
||||
return ChannelHandlers.wrap(handler, url);
|
||||
}
|
||||
|
||||
/**
|
||||
* init reconnect thread
|
||||
*/
|
||||
private synchronized void initConnectStatusCheckCommand(){
|
||||
//reconnect=false to close reconnect
|
||||
int reconnect = getReconnectParam(getUrl());
|
||||
if(reconnect > 0 && (reconnectExecutorFuture == null || reconnectExecutorFuture.isCancelled())){
|
||||
Runnable connectStatusCheckCommand = new Runnable() {
|
||||
public void run() {
|
||||
try {
|
||||
if (! isConnected()) {
|
||||
connect();
|
||||
} else {
|
||||
lastConnectedTime = System.currentTimeMillis();
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
String errorMsg = "client reconnect to "+getUrl().getAddress()+" find error . url: "+ getUrl();
|
||||
// wait registry sync provider list
|
||||
if (System.currentTimeMillis() - lastConnectedTime > shutdown_timeout){
|
||||
if (!reconnect_error_log_flag.get()){
|
||||
reconnect_error_log_flag.set(true);
|
||||
logger.error(errorMsg, t);
|
||||
return ;
|
||||
}
|
||||
}
|
||||
if ( reconnect_count.getAndIncrement() % reconnect_warning_period == 0){
|
||||
//logger.warn(errorMsg, t);
|
||||
logger.warn(errorMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
reconnectExecutorFuture = reconnectExecutorService.scheduleWithFixedDelay(connectStatusCheckCommand, reconnect, reconnect, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param url
|
||||
* @return 0-false
|
||||
*/
|
||||
private static int getReconnectParam(URL url){
|
||||
int reconnect ;
|
||||
String param = url.getParameter(Constants.RECONNECT_KEY);
|
||||
if (param == null || param.length()==0 || "true".equalsIgnoreCase(param)){
|
||||
reconnect = Constants.DEFAULT_RECONNECT_PERIOD;
|
||||
}else if ("false".equalsIgnoreCase(param)){
|
||||
reconnect = 0;
|
||||
} else {
|
||||
try{
|
||||
reconnect = Integer.parseInt(param);
|
||||
}catch (Exception e) {
|
||||
throw new IllegalArgumentException("reconnect param must be nonnegative integer or false/true. input is:"+param);
|
||||
}
|
||||
if(reconnect < 0){
|
||||
throw new IllegalArgumentException("reconnect param must be nonnegative integer or false/true. input is:"+param);
|
||||
}
|
||||
}
|
||||
return reconnect;
|
||||
}
|
||||
|
||||
private synchronized void destroyConnectStatusCheckCommand(){
|
||||
try {
|
||||
if (reconnectExecutorFuture != null && ! reconnectExecutorFuture.isDone()){
|
||||
reconnectExecutorFuture.cancel(true);
|
||||
reconnectExecutorService.purge();
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
logger.warn(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
protected ExecutorService createExecutor() {
|
||||
return Executors.newCachedThreadPool(new NamedThreadFactory(CLIENT_THREAD_POOL_NAME + CLIENT_THREAD_POOL_ID.incrementAndGet() + "-" + getUrl().getAddress(), true));
|
||||
}
|
||||
|
||||
public InetSocketAddress getConnectAddress() {
|
||||
return new InetSocketAddress(NetUtils.filterLocalHost(getUrl().getHost()), getUrl().getPort());
|
||||
}
|
||||
|
||||
public InetSocketAddress getRemoteAddress() {
|
||||
Channel channel = getChannel();
|
||||
if (channel == null)
|
||||
return getUrl().toInetSocketAddress();
|
||||
return channel.getRemoteAddress();
|
||||
}
|
||||
|
||||
public InetSocketAddress getLocalAddress() {
|
||||
Channel channel = getChannel();
|
||||
if (channel == null)
|
||||
return InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 0);
|
||||
return channel.getLocalAddress();
|
||||
}
|
||||
|
||||
public boolean isConnected() {
|
||||
Channel channel = getChannel();
|
||||
if (channel == null)
|
||||
return false;
|
||||
return channel.isConnected();
|
||||
}
|
||||
|
||||
public Object getAttribute(String key) {
|
||||
Channel channel = getChannel();
|
||||
if (channel == null)
|
||||
return null;
|
||||
return channel.getAttribute(key);
|
||||
}
|
||||
|
||||
public void setAttribute(String key, Object value) {
|
||||
Channel channel = getChannel();
|
||||
if (channel == null)
|
||||
return;
|
||||
channel.setAttribute(key, value);
|
||||
}
|
||||
|
||||
public void removeAttribute(String key) {
|
||||
Channel channel = getChannel();
|
||||
if (channel == null)
|
||||
return;
|
||||
channel.removeAttribute(key);
|
||||
}
|
||||
|
||||
public boolean hasAttribute(String key) {
|
||||
Channel channel = getChannel();
|
||||
if (channel == null)
|
||||
return false;
|
||||
return channel.hasAttribute(key);
|
||||
}
|
||||
|
||||
public void send(Object message, boolean sent) throws RemotingException {
|
||||
if (send_reconnect && !isConnected()){
|
||||
connect();
|
||||
}
|
||||
Channel channel = getChannel();
|
||||
//TODO getChannel返回的状态是否包含null需要改进
|
||||
if (channel == null || ! channel.isConnected()) {
|
||||
throw new RemotingException(this, "message can not send, because channel is closed . url:" + getUrl());
|
||||
}
|
||||
channel.send(message, sent);
|
||||
}
|
||||
|
||||
protected void connect() throws RemotingException {
|
||||
connectLock.lock();
|
||||
try {
|
||||
if (isConnected()) {
|
||||
return;
|
||||
}
|
||||
initConnectStatusCheckCommand();
|
||||
doConnect();
|
||||
if (! isConnected()) {
|
||||
throw new RemotingException(this, "Failed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " "
|
||||
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()
|
||||
+ ", cause: Connect wait timeout: " + getTimeout() + "ms.");
|
||||
} else {
|
||||
if (logger.isInfoEnabled()){
|
||||
logger.info("Successed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " "
|
||||
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()
|
||||
+ ", channel is " + this.getChannel());
|
||||
}
|
||||
}
|
||||
reconnect_count.set(0);
|
||||
reconnect_error_log_flag.set(false);
|
||||
} catch (RemotingException e) {
|
||||
throw e;
|
||||
} catch (Throwable e) {
|
||||
throw new RemotingException(this, "Failed connect to server " + getRemoteAddress() + " from " + getClass().getSimpleName() + " "
|
||||
+ NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion()
|
||||
+ ", cause: " + e.getMessage(), e);
|
||||
} finally {
|
||||
connectLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
connectLock.lock();
|
||||
try {
|
||||
destroyConnectStatusCheckCommand();
|
||||
try {
|
||||
Channel channel = getChannel();
|
||||
if (channel != null) {
|
||||
channel.close();
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
logger.warn(e.getMessage(), e);
|
||||
}
|
||||
try {
|
||||
doDisConnect();
|
||||
} catch (Throwable e) {
|
||||
logger.warn(e.getMessage(), e);
|
||||
}
|
||||
} finally {
|
||||
connectLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
public void reconnect() throws RemotingException {
|
||||
disconnect();
|
||||
connect();
|
||||
}
|
||||
|
||||
public void close() {
|
||||
try {
|
||||
if (executor != null) {
|
||||
ExecutorUtil.shutdownNow(executor, 100);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
logger.warn(e.getMessage(), e);
|
||||
}
|
||||
try {
|
||||
super.close();
|
||||
} catch (Throwable e) {
|
||||
logger.warn(e.getMessage(), e);
|
||||
}
|
||||
try {
|
||||
disconnect();
|
||||
} catch (Throwable e) {
|
||||
logger.warn(e.getMessage(), e);
|
||||
}
|
||||
try {
|
||||
doClose();
|
||||
} catch (Throwable e) {
|
||||
logger.warn(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void close(int timeout) {
|
||||
ExecutorUtil.gracefulShutdown(executor ,timeout);
|
||||
close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getClass().getName() + " [" + getLocalAddress() + " -> " + getRemoteAddress() + "]";
|
||||
}
|
||||
|
||||
/**
|
||||
* Open client.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
protected abstract void doOpen() throws Throwable;
|
||||
|
||||
/**
|
||||
* Close client.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
protected abstract void doClose() throws Throwable;
|
||||
|
||||
/**
|
||||
* Connect to server.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
protected abstract void doConnect() throws Throwable;
|
||||
|
||||
/**
|
||||
* disConnect to server.
|
||||
*
|
||||
* @throws Throwable
|
||||
*/
|
||||
protected abstract void doDisConnect() throws Throwable;
|
||||
|
||||
/**
|
||||
* Get the connected channel.
|
||||
*
|
||||
* @return channel
|
||||
*/
|
||||
protected abstract Channel getChannel();
|
||||
|
||||
}
|
||||
37
comm/Kernel/src/com/chuanglan/sms/request/SmsBalanceRequest.java
Executable file
37
comm/Kernel/src/com/chuanglan/sms/request/SmsBalanceRequest.java
Executable file
@@ -0,0 +1,37 @@
|
||||
package com.chuanglan.sms.request;
|
||||
|
||||
public class SmsBalanceRequest {
|
||||
/**
|
||||
* 用户账号,必填
|
||||
*/
|
||||
private String account;
|
||||
/**
|
||||
* 用户密码,必填
|
||||
*/
|
||||
private String password;
|
||||
|
||||
public SmsBalanceRequest() {
|
||||
|
||||
}
|
||||
public SmsBalanceRequest(String account, String password) {
|
||||
super();
|
||||
this.account = account;
|
||||
this.password = password;
|
||||
|
||||
}
|
||||
public String getAccount() {
|
||||
return account;
|
||||
}
|
||||
public void setAccount(String account) {
|
||||
this.account = account;
|
||||
}
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
48
comm/Kernel/src/com/chuanglan/sms/request/SmsPullRequest.java
Executable file
48
comm/Kernel/src/com/chuanglan/sms/request/SmsPullRequest.java
Executable file
@@ -0,0 +1,48 @@
|
||||
package com.chuanglan.sms.request;
|
||||
|
||||
public class SmsPullRequest {
|
||||
/**
|
||||
* 用户账号,必填
|
||||
*/
|
||||
private String account;
|
||||
/**
|
||||
* 用户密码,必填
|
||||
*/
|
||||
private String password;
|
||||
/**
|
||||
* 拉取个数(最大100,默认20),选填
|
||||
*/
|
||||
private String count;
|
||||
|
||||
public SmsPullRequest() {
|
||||
|
||||
}
|
||||
public SmsPullRequest(String account, String password,String count) {
|
||||
super();
|
||||
this.account = account;
|
||||
this.password = password;
|
||||
this.count = count;
|
||||
|
||||
}
|
||||
public String getAccount() {
|
||||
return account;
|
||||
}
|
||||
public void setAccount(String account) {
|
||||
this.account = account;
|
||||
}
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
public String getCount() {
|
||||
return count;
|
||||
}
|
||||
public void setCount(String count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
48
comm/Kernel/src/com/chuanglan/sms/request/SmsReportRequest.java
Executable file
48
comm/Kernel/src/com/chuanglan/sms/request/SmsReportRequest.java
Executable file
@@ -0,0 +1,48 @@
|
||||
package com.chuanglan.sms.request;
|
||||
|
||||
public class SmsReportRequest {
|
||||
/**
|
||||
* 用户账号,必填
|
||||
*/
|
||||
private String account;
|
||||
/**
|
||||
* 用户密码,必填
|
||||
*/
|
||||
private String password;
|
||||
/**
|
||||
* 拉取个数(最大100,默认20),选填
|
||||
*/
|
||||
private String count;
|
||||
|
||||
public SmsReportRequest() {
|
||||
|
||||
}
|
||||
public SmsReportRequest(String account, String password,String count) {
|
||||
super();
|
||||
this.account = account;
|
||||
this.password = password;
|
||||
this.count = count;
|
||||
|
||||
}
|
||||
public String getAccount() {
|
||||
return account;
|
||||
}
|
||||
public void setAccount(String account) {
|
||||
this.account = account;
|
||||
}
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
public String getCount() {
|
||||
return count;
|
||||
}
|
||||
public void setCount(String count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
127
comm/Kernel/src/com/chuanglan/sms/request/SmsSendRequest.java
Executable file
127
comm/Kernel/src/com/chuanglan/sms/request/SmsSendRequest.java
Executable file
@@ -0,0 +1,127 @@
|
||||
package com.chuanglan.sms.request;
|
||||
|
||||
public class SmsSendRequest {
|
||||
/**
|
||||
* 用户账号,必填
|
||||
*/
|
||||
private String account;
|
||||
/**
|
||||
* 用户密码,必填
|
||||
*/
|
||||
private String password;
|
||||
/**
|
||||
* 短信内容。长度不能超过536个字符,必填
|
||||
*/
|
||||
private String msg;
|
||||
/**
|
||||
* 机号码。多个手机号码使用英文逗号分隔,必填
|
||||
*/
|
||||
private String phone;
|
||||
|
||||
|
||||
/**
|
||||
* 定时发送短信时间。格式为yyyyMMddHHmm,值小于或等于当前时间则立即发送,默认立即发送,选填
|
||||
*/
|
||||
private String sendtime;
|
||||
/**
|
||||
* 是否需要状态报告(默认false),选填
|
||||
*/
|
||||
private String report;
|
||||
/**
|
||||
* 下发短信号码扩展码,纯数字,建议1-3位,选填
|
||||
*/
|
||||
private String extend;
|
||||
/**
|
||||
* 该条短信在您业务系统内的ID,如订单号或者短信发送记录流水号,选填
|
||||
*/
|
||||
private String uid;
|
||||
|
||||
public SmsSendRequest() {
|
||||
|
||||
}
|
||||
public SmsSendRequest(String account, String password, String msg, String phone) {
|
||||
super();
|
||||
this.account = account;
|
||||
this.password = password;
|
||||
this.msg = msg;
|
||||
this.phone = phone;
|
||||
}
|
||||
public SmsSendRequest(String account, String password, String msg, String phone, String report) {
|
||||
super();
|
||||
this.account = account;
|
||||
this.password = password;
|
||||
this.msg = msg;
|
||||
this.phone = phone;
|
||||
this.report=report;
|
||||
}
|
||||
|
||||
public SmsSendRequest(String account, String password, String msg, String phone, String report,String sendtime) {
|
||||
super();
|
||||
this.account = account;
|
||||
this.password = password;
|
||||
this.msg = msg;
|
||||
this.phone = phone;
|
||||
this.sendtime=sendtime;
|
||||
this.report=report;
|
||||
}
|
||||
public SmsSendRequest(String account, String password, String msg, String phone, String sendtime,String report,String uid) {
|
||||
super();
|
||||
this.account = account;
|
||||
this.password = password;
|
||||
this.msg = msg;
|
||||
this.phone = phone;
|
||||
this.sendtime=sendtime;
|
||||
this.report=report;
|
||||
this.uid=uid;
|
||||
}
|
||||
public String getAccount() {
|
||||
return account;
|
||||
}
|
||||
public void setAccount(String account) {
|
||||
this.account = account;
|
||||
}
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
public String getPhone() {
|
||||
return phone;
|
||||
}
|
||||
public void setPhone(String phone) {
|
||||
this.phone = phone;
|
||||
}
|
||||
public String getSendtime() {
|
||||
return sendtime;
|
||||
}
|
||||
public void setSendtime(String sendtime) {
|
||||
this.sendtime = sendtime;
|
||||
}
|
||||
public String getReport() {
|
||||
return report;
|
||||
}
|
||||
public void setReport(String report) {
|
||||
this.report = report;
|
||||
}
|
||||
public String getExtend() {
|
||||
return extend;
|
||||
}
|
||||
public void setExtend(String extend) {
|
||||
this.extend = extend;
|
||||
}
|
||||
public String getUid() {
|
||||
return uid;
|
||||
}
|
||||
public void setUid(String uid) {
|
||||
this.uid = uid;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
118
comm/Kernel/src/com/chuanglan/sms/request/SmsVariableRequest.java
Executable file
118
comm/Kernel/src/com/chuanglan/sms/request/SmsVariableRequest.java
Executable file
@@ -0,0 +1,118 @@
|
||||
package com.chuanglan.sms.request;
|
||||
/**
|
||||
|
||||
* @Description:变量短信发送实体类
|
||||
*/
|
||||
public class SmsVariableRequest {
|
||||
/**
|
||||
* 用户账号,必填
|
||||
*/
|
||||
private String account;
|
||||
/**
|
||||
* 用户密码,必填
|
||||
*/
|
||||
private String password;
|
||||
/**
|
||||
* 短信内容。长度不能超过536个字符,必填
|
||||
*/
|
||||
private String msg;
|
||||
/**
|
||||
* 手机号码和变量参数,多组参数使用英文分号;区分,必填
|
||||
*/
|
||||
private String params;
|
||||
|
||||
/**
|
||||
* 定时发送短信时间。格式为yyyyMMddHHmm,值小于或等于当前时间则立即发送,默认立即发送,选填
|
||||
*/
|
||||
private String sendtime;
|
||||
/**
|
||||
* 是否需要状态报告(默认false),选填
|
||||
*/
|
||||
private String report;
|
||||
/**
|
||||
* 下发短信号码扩展码,纯数字,建议1-3位,选填
|
||||
*/
|
||||
private String extend;
|
||||
/**
|
||||
* 该条短信在您业务系统内的ID,如订单号或者短信发送记录流水号,选填
|
||||
*/
|
||||
private String uid;
|
||||
|
||||
public SmsVariableRequest() {
|
||||
|
||||
}
|
||||
public SmsVariableRequest(String account, String password, String msg, String params) {
|
||||
super();
|
||||
this.account = account;
|
||||
this.password = password;
|
||||
this.msg = msg;
|
||||
this.params = params;
|
||||
}
|
||||
public SmsVariableRequest(String account, String password, String msg, String params, String report) {
|
||||
super();
|
||||
this.account = account;
|
||||
this.password = password;
|
||||
this.msg = msg;
|
||||
this.params = params;
|
||||
this.report = report;
|
||||
}
|
||||
// public SmsVarableRequest(String account, String password, String msg, String params, String sendtime) {
|
||||
// super();
|
||||
// this.account = account;
|
||||
// this.password = password;
|
||||
// this.msg = msg;
|
||||
// this.params = params;
|
||||
// this.sendtime = sendtime;
|
||||
// }
|
||||
public String getAccount() {
|
||||
return account;
|
||||
}
|
||||
public void setAccount(String account) {
|
||||
this.account = account;
|
||||
}
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public String getSendtime() {
|
||||
return sendtime;
|
||||
}
|
||||
public void setSendtime(String sendtime) {
|
||||
this.sendtime = sendtime;
|
||||
}
|
||||
public String getReport() {
|
||||
return report;
|
||||
}
|
||||
public void setReport(String report) {
|
||||
this.report = report;
|
||||
}
|
||||
public String getExtend() {
|
||||
return extend;
|
||||
}
|
||||
public void setExtend(String extend) {
|
||||
this.extend = extend;
|
||||
}
|
||||
public String getUid() {
|
||||
return uid;
|
||||
}
|
||||
public void setUid(String uid) {
|
||||
this.uid = uid;
|
||||
}
|
||||
public String getParams() {
|
||||
return params;
|
||||
}
|
||||
public void setParams(String params) {
|
||||
this.params = params;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
58
comm/Kernel/src/com/chuanglan/sms/response/SmsBalanceResponse.java
Executable file
58
comm/Kernel/src/com/chuanglan/sms/response/SmsBalanceResponse.java
Executable file
@@ -0,0 +1,58 @@
|
||||
package com.chuanglan.sms.response;
|
||||
/**
|
||||
|
||||
* @Description:账号余额响应实体类
|
||||
*/
|
||||
public class SmsBalanceResponse {
|
||||
/**
|
||||
* 响应时间
|
||||
*/
|
||||
private String time;
|
||||
/**
|
||||
* 消息id
|
||||
*/
|
||||
private String balance;
|
||||
/**
|
||||
* 状态码说明(成功返回空)
|
||||
*/
|
||||
private String errorMsg;
|
||||
/**
|
||||
* 状态码(详细参考提交响应状态码)
|
||||
*/
|
||||
private String code;
|
||||
public String getTime() {
|
||||
return time;
|
||||
}
|
||||
public void setTime(String time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public String getBalance() {
|
||||
return balance;
|
||||
}
|
||||
public void setBalance(String balance) {
|
||||
this.balance = balance;
|
||||
}
|
||||
public String getErrorMsg() {
|
||||
return errorMsg;
|
||||
}
|
||||
public void setErrorMsg(String errorMsg) {
|
||||
this.errorMsg = errorMsg;
|
||||
}
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SmsBalanceResponse [time=" + time + ", balance=" + balance + ", errorMsg=" + errorMsg + ", code=" + code
|
||||
+ "]";
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
103
comm/Kernel/src/com/chuanglan/sms/response/SmsPullResponse.java
Executable file
103
comm/Kernel/src/com/chuanglan/sms/response/SmsPullResponse.java
Executable file
@@ -0,0 +1,103 @@
|
||||
package com.chuanglan.sms.response;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
|
||||
* @Description:上行明细响应实体类
|
||||
*/
|
||||
public class SmsPullResponse {
|
||||
/**
|
||||
* 请求状态
|
||||
*/
|
||||
private String ret;
|
||||
/**
|
||||
* 请求错误描述
|
||||
*/
|
||||
private String error;
|
||||
/**
|
||||
* 上行明细结果
|
||||
*/
|
||||
private List<Result> result;
|
||||
|
||||
|
||||
public String getRet() {
|
||||
return ret;
|
||||
}
|
||||
|
||||
public void setRet(String ret) {
|
||||
this.ret = ret;
|
||||
}
|
||||
|
||||
public String getError() {
|
||||
return error;
|
||||
}
|
||||
|
||||
public void setError(String error) {
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
public List<Result> getResult() {
|
||||
return result;
|
||||
}
|
||||
|
||||
public void setResult(List<Result> result) {
|
||||
this.result = result;
|
||||
}
|
||||
static class Result{
|
||||
/**
|
||||
* 上行时间
|
||||
*/
|
||||
private String moTime;
|
||||
/**
|
||||
* 平台通道码
|
||||
*/
|
||||
private String spCode;
|
||||
/**
|
||||
* 上行号码
|
||||
*/
|
||||
private String mobile;
|
||||
/**
|
||||
* 运营商通道码
|
||||
*/
|
||||
private String destCode;
|
||||
/**
|
||||
* 上行内容
|
||||
*/
|
||||
private String messageContent;
|
||||
public String getMoTime() {
|
||||
return moTime;
|
||||
}
|
||||
public void setMoTime(String moTime) {
|
||||
this.moTime = moTime;
|
||||
}
|
||||
public String getSpCode() {
|
||||
return spCode;
|
||||
}
|
||||
public void setSpCode(String spCode) {
|
||||
this.spCode = spCode;
|
||||
}
|
||||
public String getMobile() {
|
||||
return mobile;
|
||||
}
|
||||
public void setMobile(String mobile) {
|
||||
this.mobile = mobile;
|
||||
}
|
||||
public String getDestCode() {
|
||||
return destCode;
|
||||
}
|
||||
public void setDestCode(String destCode) {
|
||||
this.destCode = destCode;
|
||||
}
|
||||
public String getMessageContent() {
|
||||
return messageContent;
|
||||
}
|
||||
public void setMessageContent(String messageContent) {
|
||||
this.messageContent = messageContent;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
115
comm/Kernel/src/com/chuanglan/sms/response/SmsReportResponse.java
Executable file
115
comm/Kernel/src/com/chuanglan/sms/response/SmsReportResponse.java
Executable file
@@ -0,0 +1,115 @@
|
||||
package com.chuanglan.sms.response;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description:状态报告响应实体类
|
||||
*/
|
||||
public class SmsReportResponse {
|
||||
/**
|
||||
* 请求状态
|
||||
*/
|
||||
private String ret;
|
||||
/**
|
||||
* 请求错误描述
|
||||
*/
|
||||
private String error;
|
||||
/**
|
||||
* 上行明细结果
|
||||
*/
|
||||
private List<Result> result;
|
||||
|
||||
|
||||
|
||||
public String getRet() {
|
||||
return ret;
|
||||
}
|
||||
|
||||
public void setRet(String ret) {
|
||||
this.ret = ret;
|
||||
}
|
||||
|
||||
public String getError() {
|
||||
return error;
|
||||
}
|
||||
|
||||
public void setError(String error) {
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
public List<Result> getResult() {
|
||||
return result;
|
||||
}
|
||||
|
||||
public void setResult(List<Result> result) {
|
||||
this.result = result;
|
||||
}
|
||||
static class Result{
|
||||
/**
|
||||
* 消息ID
|
||||
*/
|
||||
private String msgId;
|
||||
/**
|
||||
* 状态更新时间
|
||||
*/
|
||||
private String reportTime;
|
||||
/**
|
||||
* 接收短信的手机号码
|
||||
*/
|
||||
private String mobile;
|
||||
/**
|
||||
* 状态(详细参考状态报告状态码)
|
||||
*/
|
||||
private String status;
|
||||
/**
|
||||
* 状态说明
|
||||
*/
|
||||
private String statusDesc;
|
||||
/**
|
||||
* 拉取个数
|
||||
*/
|
||||
private String count;
|
||||
public String getMsgId() {
|
||||
return msgId;
|
||||
}
|
||||
public void setMsgId(String msgId) {
|
||||
this.msgId = msgId;
|
||||
}
|
||||
public String getReportTime() {
|
||||
return reportTime;
|
||||
}
|
||||
public void setReportTime(String reportTime) {
|
||||
this.reportTime = reportTime;
|
||||
}
|
||||
public String getMobile() {
|
||||
return mobile;
|
||||
}
|
||||
public void setMobile(String mobile) {
|
||||
this.mobile = mobile;
|
||||
}
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
public String getStatusDesc() {
|
||||
return statusDesc;
|
||||
}
|
||||
public void setStatusDesc(String statusDesc) {
|
||||
this.statusDesc = statusDesc;
|
||||
}
|
||||
public String getCount() {
|
||||
return count;
|
||||
}
|
||||
public void setCount(String count) {
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
56
comm/Kernel/src/com/chuanglan/sms/response/SmsSendResponse.java
Executable file
56
comm/Kernel/src/com/chuanglan/sms/response/SmsSendResponse.java
Executable file
@@ -0,0 +1,56 @@
|
||||
package com.chuanglan.sms.response;
|
||||
/**
|
||||
*
|
||||
* @Description:普通短信发送响应实体类
|
||||
*/
|
||||
public class SmsSendResponse {
|
||||
/**
|
||||
* 响应时间
|
||||
*/
|
||||
private String time;
|
||||
/**
|
||||
* 消息id
|
||||
*/
|
||||
private String msgId;
|
||||
/**
|
||||
* 状态码说明(成功返回空)
|
||||
*/
|
||||
private String errorMsg;
|
||||
/**
|
||||
* 状态码(详细参考提交响应状态码)
|
||||
*/
|
||||
private String code;
|
||||
public String getTime() {
|
||||
return time;
|
||||
}
|
||||
public void setTime(String time) {
|
||||
this.time = time;
|
||||
}
|
||||
public String getMsgId() {
|
||||
return msgId;
|
||||
}
|
||||
public void setMsgId(String msgId) {
|
||||
this.msgId = msgId;
|
||||
}
|
||||
public String getErrorMsg() {
|
||||
return errorMsg;
|
||||
}
|
||||
public void setErrorMsg(String errorMsg) {
|
||||
this.errorMsg = errorMsg;
|
||||
}
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SmsSingleResponse [time=" + time + ", msgId=" + msgId + ", errorMsg=" + errorMsg + ", code=" + code
|
||||
+ "]";
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
77
comm/Kernel/src/com/chuanglan/sms/response/SmsVariableResponse.java
Executable file
77
comm/Kernel/src/com/chuanglan/sms/response/SmsVariableResponse.java
Executable file
@@ -0,0 +1,77 @@
|
||||
package com.chuanglan.sms.response;
|
||||
/**
|
||||
*
|
||||
* @Description:变量短信发送响应实体类
|
||||
*/
|
||||
public class SmsVariableResponse {
|
||||
/**
|
||||
* 响应时间
|
||||
*/
|
||||
private String time;
|
||||
/**
|
||||
* 消息id
|
||||
*/
|
||||
private String msgId;
|
||||
/**
|
||||
* 状态码说明(成功返回空)
|
||||
*/
|
||||
private String errorMsg;
|
||||
/**
|
||||
* 失败的个数
|
||||
*/
|
||||
private String failNum;
|
||||
/**
|
||||
* 成功的个数
|
||||
*/
|
||||
private String successNum;
|
||||
/**
|
||||
* 状态码(详细参考提交响应状态码)
|
||||
*/
|
||||
private String code;
|
||||
public String getTime() {
|
||||
return time;
|
||||
}
|
||||
public void setTime(String time) {
|
||||
this.time = time;
|
||||
}
|
||||
public String getMsgId() {
|
||||
return msgId;
|
||||
}
|
||||
public void setMsgId(String msgId) {
|
||||
this.msgId = msgId;
|
||||
}
|
||||
public String getErrorMsg() {
|
||||
return errorMsg;
|
||||
}
|
||||
public void setErrorMsg(String errorMsg) {
|
||||
this.errorMsg = errorMsg;
|
||||
}
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
public String getFailNum() {
|
||||
return failNum;
|
||||
}
|
||||
public void setFailNum(String failNum) {
|
||||
this.failNum = failNum;
|
||||
}
|
||||
public String getSuccessNum() {
|
||||
return successNum;
|
||||
}
|
||||
public void setSuccessNum(String successNum) {
|
||||
this.successNum = successNum;
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SmsVarableResponse [time=" + time + ", msgId=" + msgId + ", errorMsg=" + errorMsg + ", failNum="
|
||||
+ failNum + ", successNum=" + successNum + ", code=" + code + "]";
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
69
comm/Kernel/src/com/chuanglan/sms/util/ChuangLanSmsUtil.java
Executable file
69
comm/Kernel/src/com/chuanglan/sms/util/ChuangLanSmsUtil.java
Executable file
@@ -0,0 +1,69 @@
|
||||
package com.chuanglan.sms.util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
//import java.io.PrintWriter;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description:HTTP 请求
|
||||
*/
|
||||
public class ChuangLanSmsUtil {
|
||||
|
||||
/**
|
||||
*
|
||||
* @author tianyh
|
||||
* @Description
|
||||
* @param path
|
||||
* @param postContent
|
||||
* @return String
|
||||
* @throws
|
||||
*/
|
||||
public static String sendSmsByPost(String path, String postContent) {
|
||||
URL url = null;
|
||||
try {
|
||||
url = new URL(path);
|
||||
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
|
||||
httpURLConnection.setRequestMethod("POST");// 提交模式
|
||||
httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
|
||||
httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
|
||||
// 发送POST请求必须设置如下两行
|
||||
httpURLConnection.setDoOutput(true);
|
||||
httpURLConnection.setDoInput(true);
|
||||
httpURLConnection.setRequestProperty("Charset", "UTF-8");
|
||||
httpURLConnection.setRequestProperty("Content-Type", "application/json");
|
||||
|
||||
// PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
|
||||
// printWriter.write(postContent);
|
||||
// printWriter.flush();
|
||||
|
||||
httpURLConnection.connect();
|
||||
OutputStream os=httpURLConnection.getOutputStream();
|
||||
os.write(postContent.getBytes("UTF-8"));
|
||||
os.flush();
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int httpRspCode = httpURLConnection.getResponseCode();
|
||||
if (httpRspCode == HttpURLConnection.HTTP_OK) {
|
||||
// 开始获取数据
|
||||
BufferedReader br = new BufferedReader(
|
||||
new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
|
||||
String line = null;
|
||||
while ((line = br.readLine()) != null) {
|
||||
sb.append(line);
|
||||
}
|
||||
br.close();
|
||||
return sb.toString();
|
||||
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
8
comm/Kernel/src/kernel/annotation/BeanFieldName.java
Executable file
8
comm/Kernel/src/kernel/annotation/BeanFieldName.java
Executable file
@@ -0,0 +1,8 @@
|
||||
package kernel.annotation;
|
||||
|
||||
@java.lang.annotation.Documented
|
||||
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
|
||||
@java.lang.annotation.Target({java.lang.annotation.ElementType.FIELD, java.lang.annotation.ElementType.METHOD})
|
||||
public @interface BeanFieldName {
|
||||
String value();
|
||||
}
|
||||
12
comm/Kernel/src/kernel/annotation/CustomCache.java
Executable file
12
comm/Kernel/src/kernel/annotation/CustomCache.java
Executable file
@@ -0,0 +1,12 @@
|
||||
package kernel.annotation;
|
||||
|
||||
@java.lang.annotation.Documented
|
||||
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
|
||||
@java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
|
||||
public @interface CustomCache {
|
||||
String keyPrefix();
|
||||
|
||||
String key();
|
||||
|
||||
int timmeout() default 0;
|
||||
}
|
||||
97
comm/Kernel/src/kernel/bo/EntityObject.java
Executable file
97
comm/Kernel/src/kernel/bo/EntityObject.java
Executable file
@@ -0,0 +1,97 @@
|
||||
package kernel.bo;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Date;
|
||||
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* 实体抽象类
|
||||
*
|
||||
*/
|
||||
public class EntityObject implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = -6624393812017741464L;
|
||||
|
||||
private Serializable id;
|
||||
|
||||
private int entityVersion;
|
||||
|
||||
private Date timestamp;
|
||||
|
||||
public Serializable getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Serializable id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public int getEntityVersion() {
|
||||
return entityVersion;
|
||||
}
|
||||
|
||||
public void setEntityVersion(int entityVersion) {
|
||||
this.entityVersion = entityVersion;
|
||||
}
|
||||
|
||||
public Date getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
public void setTimestamp(Date timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
// @Override
|
||||
public String toString() {
|
||||
return ClassUtils.getShortName(getClass()) + ": id=" + getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to establish identity based on id if both exist. If either id
|
||||
* does not exist use Object.equals().
|
||||
*
|
||||
* @see java.lang.Object#equals(java.lang.Object)
|
||||
*/
|
||||
public boolean equals(Object other) {
|
||||
if (other == this) {
|
||||
return true;
|
||||
}
|
||||
if (other == null) {
|
||||
return false;
|
||||
}
|
||||
if (!(other instanceof EntityObject)) {
|
||||
return false;
|
||||
}
|
||||
// 即便是继承关系,由于数据逻辑存在依赖关系,必须是同class才行
|
||||
if(!this.getClass().equals(other.getClass())){
|
||||
return false;
|
||||
}
|
||||
EntityObject entity = (EntityObject) other;
|
||||
if (id == null || entity.getId() == null) {
|
||||
return false;
|
||||
}
|
||||
return id.equals(entity.getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Use ID if it exists to establish hash code, otherwise fall back to
|
||||
* Object.hashCode(). Based on the same information as equals, so if that
|
||||
* changes, this will. N.B. this follows the contract of Object.hashCode(),
|
||||
* but will cause problems for anyone adding an unsaved {@link Entity} to a
|
||||
* Set because Set.contains() will almost certainly return false for the
|
||||
* {@link Entity} after it is saved. Spring Batch does not store any of its
|
||||
* entities in Sets as a matter of course, so internally this is consistent.
|
||||
* Clients should not be exposed to unsaved entities.
|
||||
*
|
||||
* @see java.lang.Object#hashCode()
|
||||
*/
|
||||
public int hashCode() {
|
||||
if (id == null) {
|
||||
return super.hashCode();
|
||||
}
|
||||
return 39 + 29 * getClass().hashCode() + 87 * id.hashCode();
|
||||
}
|
||||
|
||||
}
|
||||
86
comm/Kernel/src/kernel/cache/CustomCacheMethodProcessor.java
vendored
Executable file
86
comm/Kernel/src/kernel/cache/CustomCacheMethodProcessor.java
vendored
Executable file
@@ -0,0 +1,86 @@
|
||||
package kernel.cache;
|
||||
|
||||
import kernel.annotation.CustomCache;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.aop.support.AopUtils;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.core.annotation.AnnotatedElementUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @Description: 在当前的应用下需要配置进 bean.xml 才会生效 TODO
|
||||
* 参考资料:
|
||||
* https://blog.csdn.net/qq_30095631/article/details/103669089
|
||||
*
|
||||
* @author caster
|
||||
* @date 2023年4月26日 下午10:25:32
|
||||
*
|
||||
*/
|
||||
public class CustomCacheMethodProcessor implements BeanPostProcessor,
|
||||
ApplicationContextAware, SmartInitializingSingleton {
|
||||
|
||||
protected Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
private ConfigurableApplicationContext applicationContext;
|
||||
|
||||
private List<Method> allCachedMethodList = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public final void setApplicationContext(ApplicationContext applicationContext)
|
||||
throws BeansException {
|
||||
this.applicationContext = (ConfigurableApplicationContext) applicationContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比 afterSingletonsInstantiated 先执行
|
||||
*
|
||||
* @param bean
|
||||
* @param beanName
|
||||
* @return
|
||||
* @throws BeansException
|
||||
*/
|
||||
@Override
|
||||
public final Object postProcessAfterInitialization(Object bean, final String beanName)
|
||||
throws BeansException {
|
||||
Class<?> beanClass = AopUtils.isAopProxy(bean) ? AopUtils.getTargetClass(bean)
|
||||
: bean.getClass();
|
||||
|
||||
Method[] uniqueDeclaredMethods = ReflectionUtils.getUniqueDeclaredMethods(beanClass);
|
||||
for (Method method : uniqueDeclaredMethods) {
|
||||
CustomCache cacheAnn = AnnotatedElementUtils.findMergedAnnotation(method, CustomCache.class);
|
||||
if (cacheAnn != null && !method.isBridge()) {
|
||||
allCachedMethodList.add(method);
|
||||
}
|
||||
}
|
||||
|
||||
return bean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当系统中所有 bean 加载成功后才会执行
|
||||
*/
|
||||
@Override
|
||||
public final void afterSingletonsInstantiated() {
|
||||
if (allCachedMethodList.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO
|
||||
|
||||
allCachedMethodList.clear();
|
||||
allCachedMethodList = null;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
67
comm/Kernel/src/kernel/cache/LocalCachePool.java
vendored
Executable file
67
comm/Kernel/src/kernel/cache/LocalCachePool.java
vendored
Executable file
@@ -0,0 +1,67 @@
|
||||
package kernel.cache;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.github.benmanes.caffeine.cache.*;
|
||||
import lombok.NonNull;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Slf4j
|
||||
public class LocalCachePool {
|
||||
|
||||
private static Map<String, Cache> cacheBucket = new ConcurrentHashMap<>();
|
||||
|
||||
public static <K, V> Cache<K, V> buildCache(String bucket, int size, int secondsTimeout, CacheLoader loader) {
|
||||
if (StrUtil.isBlank(bucket)) {
|
||||
throw new RuntimeException("错误的参数");
|
||||
}
|
||||
if (size <= 0) {
|
||||
size = 256;
|
||||
}
|
||||
|
||||
if (cacheBucket.containsKey(bucket)) {
|
||||
return cacheBucket.get(bucket);
|
||||
}
|
||||
|
||||
Caffeine<K, V> caffeine = Caffeine.newBuilder()
|
||||
//最大个数限制
|
||||
.maximumSize(size)
|
||||
//初始化容量
|
||||
.initialCapacity(size / 2)
|
||||
// 访问后过期(包括读和写)
|
||||
.expireAfterAccess(secondsTimeout, TimeUnit.SECONDS)
|
||||
// 写后过期
|
||||
.expireAfterWrite(secondsTimeout, TimeUnit.SECONDS)
|
||||
// 写后自动异步刷新
|
||||
//.refreshAfterWrite(1, TimeUnit.HOURS)
|
||||
//记录下缓存的一些统计数据,例如命中率等
|
||||
.recordStats()
|
||||
//cache对缓存写的通知回调
|
||||
.writer(new CacheWriter() {
|
||||
@Override
|
||||
public void write(Object key, Object value) {
|
||||
//log.info("key={}, CacheWriter write", key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(Object key, Object value, RemovalCause cause) {
|
||||
//log.info("key={}, cause={}, CacheWriter delete", key, cause);
|
||||
}
|
||||
});
|
||||
if (loader != null) {
|
||||
caffeine.build(loader);
|
||||
}
|
||||
|
||||
Cache cache = caffeine.build();
|
||||
|
||||
Cache existCache = cacheBucket.putIfAbsent(bucket, cache);
|
||||
if (existCache == null) {
|
||||
return cache;
|
||||
}
|
||||
|
||||
return existCache;
|
||||
}
|
||||
}
|
||||
34
comm/Kernel/src/kernel/cache/RedisLocalCache.java
vendored
Executable file
34
comm/Kernel/src/kernel/cache/RedisLocalCache.java
vendored
Executable file
@@ -0,0 +1,34 @@
|
||||
package kernel.cache;
|
||||
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import project.redis.RedisHandler;
|
||||
|
||||
public class RedisLocalCache {
|
||||
|
||||
private ConcurrentHashMap<String, Object> cache = new ConcurrentHashMap<String, Object>();
|
||||
private RedisHandler redisHandler;
|
||||
|
||||
public Object get(String key) {
|
||||
|
||||
Object obj = cache.get(key);
|
||||
if (obj != null) {
|
||||
return obj;
|
||||
}
|
||||
obj = redisHandler.get(key);
|
||||
if (obj != null) {
|
||||
cache.put(key, obj);
|
||||
return obj;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void put(String key, Object obj) {
|
||||
cache.put(key, obj);
|
||||
}
|
||||
|
||||
public void setRedisHandler(RedisHandler redisHandler) {
|
||||
this.redisHandler = redisHandler;
|
||||
}
|
||||
|
||||
}
|
||||
23
comm/Kernel/src/kernel/concurrent/ConcurrentQequestHandleStrategy.java
Executable file
23
comm/Kernel/src/kernel/concurrent/ConcurrentQequestHandleStrategy.java
Executable file
@@ -0,0 +1,23 @@
|
||||
package kernel.concurrent;
|
||||
|
||||
/**
|
||||
* 并发请求处理策略枚举类型
|
||||
*/
|
||||
public enum ConcurrentQequestHandleStrategy {
|
||||
RETURN_NONE_WAIT("立即反馈并发状态"),
|
||||
|
||||
SLEEP_THEN_RETURN("睡眠一段时间然后反馈并发状态"),
|
||||
|
||||
;
|
||||
|
||||
private String description;
|
||||
|
||||
private ConcurrentQequestHandleStrategy(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return this.description;
|
||||
}
|
||||
|
||||
}
|
||||
14
comm/Kernel/src/kernel/concurrent/ThreadPoolTaskExecutor.java
Executable file
14
comm/Kernel/src/kernel/concurrent/ThreadPoolTaskExecutor.java
Executable file
@@ -0,0 +1,14 @@
|
||||
package kernel.concurrent;
|
||||
|
||||
|
||||
public class ThreadPoolTaskExecutor extends org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor {
|
||||
|
||||
private static final long serialVersionUID = 119645098645321188L;
|
||||
|
||||
@Override
|
||||
public void execute(Runnable runnable) {
|
||||
super.execute(runnable);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
10
comm/Kernel/src/kernel/constants/DataTimeConstants.java
Executable file
10
comm/Kernel/src/kernel/constants/DataTimeConstants.java
Executable file
@@ -0,0 +1,10 @@
|
||||
package kernel.constants;
|
||||
|
||||
public interface DataTimeConstants {
|
||||
public static final String PATTERN_DATE_TIME = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
public static final String PATTERN_DAY = "yyyy-MM-dd";
|
||||
|
||||
public static final String PATTERN_DATE_MONTH = "yyyy-MM";
|
||||
|
||||
}
|
||||
48
comm/Kernel/src/kernel/constants/LocalCacheBucketKey.java
Executable file
48
comm/Kernel/src/kernel/constants/LocalCacheBucketKey.java
Executable file
@@ -0,0 +1,48 @@
|
||||
package kernel.constants;
|
||||
|
||||
/**
|
||||
* 统一放置 localCache 的 bucket 名称,放置 key 冲突,便于维护
|
||||
*/
|
||||
public interface LocalCacheBucketKey {
|
||||
//
|
||||
String GoodsSkuAttrListCache = "goodsSkuAttrListCache";
|
||||
|
||||
//
|
||||
String GoodsAttrValueLangCache = "goodsAttrValueLangCache";
|
||||
|
||||
//
|
||||
String SellerGoodsSkuCache = "sellerGoodsSkuCache";
|
||||
|
||||
//
|
||||
String GoodsAttrListBySkuCache = "goodsAttrListBySkuCache";
|
||||
|
||||
|
||||
String CountLoginByDay = "CountLoginByDay";
|
||||
|
||||
String CountRegisterByDay = "CountRegisterByDay";
|
||||
|
||||
String CountRegisterSellerByDay = "CountRegisterSellerByDay";
|
||||
|
||||
String CountOrderByDay = "CountOrderByDay";
|
||||
|
||||
String CountAllUser = "CountAllUser";
|
||||
|
||||
String CountAllSeller = "CountAllSeller";
|
||||
|
||||
String TotalProfitByDay = "TotalProfitByDay";
|
||||
|
||||
String SumWithdrawByDay = "SumWithdrawByDay";
|
||||
|
||||
String SumRechargeByDay = "SumRechargeByDay";
|
||||
|
||||
String NewRechargeByDay = "NewRechargeByDay";
|
||||
|
||||
String NewWithdrawByDay = "NewWithdrawByDay";
|
||||
|
||||
String CountWithdrawByDay = "CountWithdrawByDay";
|
||||
|
||||
String CountRechargeByDay = "CountRechargeByDay";
|
||||
|
||||
String SumSellerOrdersPrize = "SumSellerOrdersPrize";
|
||||
|
||||
}
|
||||
52
comm/Kernel/src/kernel/constants/ValueTypeEnum.java
Executable file
52
comm/Kernel/src/kernel/constants/ValueTypeEnum.java
Executable file
@@ -0,0 +1,52 @@
|
||||
package kernel.constants;
|
||||
|
||||
public enum ValueTypeEnum {
|
||||
|
||||
BYTE(1, "byte类型"),
|
||||
BYTTER(2, "Byte类型"),
|
||||
SHORT(3, "short类型"),
|
||||
SHORTER(4, "Short类型"),
|
||||
INT(5, "int类型"),
|
||||
INTEGER(6, "Integer类型"),
|
||||
LONG(7, "long类型"),
|
||||
LONGER(8, "Long类型"),
|
||||
FLOAT(9, "float类型"),
|
||||
FLOATER(10, "Float类型"),
|
||||
DOUBLE(11, "float类型"),
|
||||
DOUBLER(12, "Double类型"),
|
||||
STRING(13, "String类型"),
|
||||
DATE(14, "Date类型"),
|
||||
JAVABEAN(15, "自定义JavaBean类型"),
|
||||
|
||||
// 其他类型,例如数组
|
||||
|
||||
;
|
||||
|
||||
private int code;
|
||||
|
||||
private String description;
|
||||
|
||||
private ValueTypeEnum(int code, String description) {
|
||||
this.code = code;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public static ValueTypeEnum codeOf(int inputCode) {
|
||||
ValueTypeEnum[] values = ValueTypeEnum.values();
|
||||
for (ValueTypeEnum one : values) {
|
||||
if (inputCode == one.getCode()) {
|
||||
return one;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public int getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
}
|
||||
33
comm/Kernel/src/kernel/context/ApplicationContextHolder.java
Executable file
33
comm/Kernel/src/kernel/context/ApplicationContextHolder.java
Executable file
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package kernel.context;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.support.AbstractApplicationContext;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
|
||||
|
||||
public abstract class ApplicationContextHolder {
|
||||
|
||||
|
||||
public static AbstractApplicationContext applicationContext = null;
|
||||
|
||||
public static void launcher() {
|
||||
|
||||
applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext*.xml");
|
||||
applicationContext.registerShutdownHook();
|
||||
}
|
||||
|
||||
public static Object getBean(String name) {
|
||||
if (applicationContext == null) {
|
||||
launcher();
|
||||
}
|
||||
return applicationContext.getBean(name);
|
||||
}
|
||||
|
||||
public static ApplicationContext getApplicationContext() {
|
||||
return applicationContext;
|
||||
}
|
||||
|
||||
}
|
||||
41
comm/Kernel/src/kernel/dao/HibernateUtils.java
Executable file
41
comm/Kernel/src/kernel/dao/HibernateUtils.java
Executable file
@@ -0,0 +1,41 @@
|
||||
package kernel.dao;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
import org.hibernate.Query;
|
||||
import org.hibernate.proxy.HibernateProxy;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
|
||||
public abstract class HibernateUtils extends SQLUtils {
|
||||
|
||||
public static Object resolveRealObject(Object proxy) {
|
||||
if (proxy == null) {
|
||||
return null;
|
||||
}
|
||||
if (proxy instanceof HibernateProxy) {
|
||||
return ((HibernateProxy) proxy).getHibernateLazyInitializer().getImplementation();
|
||||
}
|
||||
return proxy;
|
||||
}
|
||||
|
||||
public static void applyParameters(Query queryObject, Map<String, Object> parameters) {
|
||||
if (!CollectionUtils.isEmpty(parameters)) {
|
||||
for (Entry<String, Object> entry : parameters.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
if (value instanceof Collection) {
|
||||
queryObject.setParameterList(key, (Collection<?>) value);
|
||||
}
|
||||
else if (value instanceof Object[]) {
|
||||
queryObject.setParameterList(key, (Object[]) value);
|
||||
}
|
||||
else {
|
||||
queryObject.setParameter(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
39
comm/Kernel/src/kernel/dao/SQLUtils.java
Executable file
39
comm/Kernel/src/kernel/dao/SQLUtils.java
Executable file
@@ -0,0 +1,39 @@
|
||||
package kernel.dao;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
|
||||
public abstract class SQLUtils {
|
||||
|
||||
/**
|
||||
* 去除hql的select 子句,未考虑union的情况,用于pagedQuery.
|
||||
*
|
||||
* @see #pagedQuery(String,int,int,Object[])
|
||||
*/
|
||||
public static String removeSelect(String hql) {
|
||||
Assert.hasText(hql);
|
||||
int beginPos = hql.toLowerCase().indexOf("from");
|
||||
Assert.isTrue(beginPos != -1, " hql : " + hql + " must has a keyword 'from'");
|
||||
return hql.substring(beginPos);
|
||||
}
|
||||
|
||||
/**
|
||||
* 去除hql的orderby 子句,用于pagedQuery.
|
||||
*
|
||||
* @see #pagedQuery(String,int,int,Object[])
|
||||
*/
|
||||
public static String removeOrders(String hql) {
|
||||
Assert.hasText(hql);
|
||||
Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
|
||||
Matcher m = p.matcher(hql);
|
||||
StringBuffer sb = new StringBuffer();
|
||||
while (m.find()) {
|
||||
m.appendReplacement(sb, "");
|
||||
}
|
||||
m.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
20
comm/Kernel/src/kernel/dbcp/LocalBasicDataSource.java
Executable file
20
comm/Kernel/src/kernel/dbcp/LocalBasicDataSource.java
Executable file
@@ -0,0 +1,20 @@
|
||||
package kernel.dbcp;
|
||||
|
||||
import org.apache.commons.dbcp.BasicDataSource;
|
||||
|
||||
import kernel.util.Endecrypt;
|
||||
|
||||
public class LocalBasicDataSource extends BasicDataSource {
|
||||
|
||||
private String KEY = "Roj6#@08SDF87323FG00%jjsd";
|
||||
|
||||
|
||||
@Override
|
||||
public synchronized void setPassword(String password) {
|
||||
Endecrypt endecrypt = new Endecrypt();
|
||||
super.setPassword(endecrypt.get3DESDecrypt(password, KEY));
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
18
comm/Kernel/src/kernel/druid/LocalDruidDataSource.java
Executable file
18
comm/Kernel/src/kernel/druid/LocalDruidDataSource.java
Executable file
@@ -0,0 +1,18 @@
|
||||
package kernel.druid;
|
||||
|
||||
import com.alibaba.druid.pool.DruidDataSource;
|
||||
|
||||
import kernel.util.Endecrypt;
|
||||
|
||||
public class LocalDruidDataSource extends DruidDataSource{
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 8682300581159171345L;
|
||||
private String KEY = "Roj6#@08SDF87323FG00%jjsd";
|
||||
// public void setPassword(String password) {
|
||||
// Endecrypt endecrypt = new Endecrypt();
|
||||
// String endecrypt3DESDecrypt = endecrypt.get3DESDecrypt(password, KEY);
|
||||
// super.setPassword(endecrypt.get3DESDecrypt(password, KEY));
|
||||
// }
|
||||
}
|
||||
34
comm/Kernel/src/kernel/exception/BusinessException.java
Executable file
34
comm/Kernel/src/kernel/exception/BusinessException.java
Executable file
@@ -0,0 +1,34 @@
|
||||
package kernel.exception;
|
||||
|
||||
public class BusinessException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1877734890673094989L;
|
||||
|
||||
private int sign;
|
||||
|
||||
public BusinessException(String message) {
|
||||
this(1, message);
|
||||
}
|
||||
|
||||
public BusinessException(int sign, String message) {
|
||||
super(message);
|
||||
this.sign = sign;
|
||||
}
|
||||
|
||||
public BusinessException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public BusinessException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public int getSign() {
|
||||
return sign;
|
||||
}
|
||||
|
||||
public void setSign(int sign) {
|
||||
this.sign = sign;
|
||||
}
|
||||
|
||||
}
|
||||
341
comm/Kernel/src/kernel/http/HttpHelper.java
Executable file
341
comm/Kernel/src/kernel/http/HttpHelper.java
Executable file
@@ -0,0 +1,341 @@
|
||||
package kernel.http;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.CookieStore;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.HttpResponseException;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.client.methods.HttpRequestBase;
|
||||
import org.apache.http.client.protocol.HttpClientContext;
|
||||
import org.apache.http.client.utils.URLEncodedUtils;
|
||||
import org.apache.http.config.Registry;
|
||||
import org.apache.http.config.RegistryBuilder;
|
||||
import org.apache.http.conn.HttpConnectionFactory;
|
||||
import org.apache.http.conn.ManagedHttpClientConnection;
|
||||
import org.apache.http.conn.routing.HttpRoute;
|
||||
import org.apache.http.conn.socket.ConnectionSocketFactory;
|
||||
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.cookie.Cookie;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.BasicCookieStore;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.conn.DefaultHttpResponseParserFactory;
|
||||
import org.apache.http.impl.conn.ManagedHttpClientConnectionFactory;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
import org.apache.http.impl.conn.SystemDefaultDnsResolver;
|
||||
import org.apache.http.impl.io.DefaultHttpRequestWriterFactory;
|
||||
import org.apache.http.io.HttpMessageWriterFactory;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.protocol.BasicHttpContext;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
import org.apache.http.ssl.SSLContexts;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
|
||||
/**
|
||||
* <p/>
|
||||
* //请求信息类型MIME每种响应类型的输出(普通文本、html 和 XML,json)。允许的响应类型应当匹配资源类中生成的 MIME 类型
|
||||
* //资源类生成的 MIME 类型应当匹配一种可接受的 MIME 类型。如果生成的 MIME 类型和可接受的 MIME 类型不 匹配,那么将 //生成
|
||||
* com.sun.jersey.api.client.UniformInterfaceException。例如,将可接受的 MIME 类型设置为
|
||||
* text/xml,而将 //生成的 MIME 类型设置为 application/xml。将生成 UniformInterfaceException。
|
||||
* //代理: new HttpHost("10.0.0.172", 80, "http");
|
||||
* <p/>
|
||||
*/
|
||||
public class HttpHelper {
|
||||
private static final Logger logger = LoggerFactory.getLogger(HttpHelper.class);
|
||||
private static Map<String, List<Cookie>> cookiesMap = Collections
|
||||
.synchronizedMap(new HashMap<String, List<Cookie>>());
|
||||
static private HttpClient httpclient;
|
||||
private static Map<String, Map<String, String>> globalParam = new HashMap<String, Map<String, String>>(5);
|
||||
private static Map<String, String> headers = new HashMap<String, String>();
|
||||
|
||||
static {
|
||||
RequestConfig config = RequestConfig.copy(RequestConfig.DEFAULT).setConnectionRequestTimeout(30000)
|
||||
.setSocketTimeout(40000).build();
|
||||
SSLContext sslcontext = SSLContexts.createSystemDefault();
|
||||
HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();
|
||||
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("http", PlainConnectionSocketFactory.INSTANCE)
|
||||
.register("https", new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE)).build();
|
||||
HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
|
||||
requestWriterFactory, new DefaultHttpResponseParserFactory());
|
||||
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry,
|
||||
connFactory, new SystemDefaultDnsResolver());
|
||||
connManager.setMaxTotal(100);
|
||||
connManager.setDefaultMaxPerRoute(100);
|
||||
httpclient = HttpClientBuilder.create().setConnectionManager(connManager).setDefaultRequestConfig(config)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过HTTP协议访问站点,并且将返回的数据转换成json对象 注意 对方返回的数据最外层对象必须是单个对象
|
||||
*
|
||||
* @param url
|
||||
* @param param
|
||||
* @param method
|
||||
* @return
|
||||
* @throws IOException
|
||||
* @throws IOException
|
||||
*/
|
||||
public static String getJSONFromHttp(String url, Map<String, Object> param, HttpMethodType method)
|
||||
throws RuntimeException {
|
||||
String rs;
|
||||
switch (method) {
|
||||
case GET: {
|
||||
rs = sendGetHttp(url, param);
|
||||
break;
|
||||
}
|
||||
case POST: {
|
||||
rs = sendPostHttp(url, param, false);
|
||||
break;
|
||||
}
|
||||
|
||||
default: {
|
||||
throw new IllegalArgumentException("HTTP访问方式设置有误");
|
||||
}
|
||||
}
|
||||
logger.debug("return is:" + rs);
|
||||
return rs == null || "".equals(rs) ? null : rs;
|
||||
}
|
||||
|
||||
public static String sendHttp(String url, Map<String, Object> param, HttpMethodType method)
|
||||
throws RuntimeException {
|
||||
switch (method) {
|
||||
case GET: {
|
||||
return sendGetHttp(url, param);
|
||||
}
|
||||
case POST: {
|
||||
return sendPostHttp(url, param, false);
|
||||
}
|
||||
default:
|
||||
throw new IllegalArgumentException("参数中的HTTP访问方式有误,只支持GET、POST、FILE");
|
||||
}
|
||||
}
|
||||
|
||||
private static final Pattern paramPat = Pattern.compile("([^&]+)=([^&]+)");
|
||||
|
||||
/**
|
||||
* 发送一个HTTP协议的GET请求
|
||||
*
|
||||
* @param url
|
||||
* @param param
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static String sendGetHttp(String url, Map<String, Object> param) throws RuntimeException {
|
||||
StringBuilder parmStr = new StringBuilder();
|
||||
if (null != param && !param.isEmpty()) {
|
||||
List<NameValuePair> parm = new ArrayList<NameValuePair>(param.size());
|
||||
for (Map.Entry<String, Object> paramEntity : param.entrySet()) {
|
||||
Object value = paramEntity.getValue();
|
||||
if (null != value && !StringUtils.isBlank(value.toString())) {
|
||||
parm.add(new BasicNameValuePair(paramEntity.getKey(), value.toString()));
|
||||
}
|
||||
}
|
||||
parmStr.append(URLEncodedUtils.format(parm, "UTF-8"));
|
||||
}
|
||||
return sendGetHttp(url, parmStr.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送一个HTTP协议的GET请求
|
||||
*
|
||||
* @param url
|
||||
* @param param
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static String sendGetHttp(String url, String param) throws RuntimeException {
|
||||
HttpContext localContext = new BasicHttpContext();
|
||||
setCookie(localContext, url);
|
||||
if (!StringUtils.isBlank(param))
|
||||
url = url + ((url.indexOf("?") > 0) ? "&" + param : "?" + param);
|
||||
url = appendGlobalParam(url, param);
|
||||
// logger.debug("远程URL:{}", url);
|
||||
// 创建HttpGet对象
|
||||
HttpGet request = new HttpGet(url);
|
||||
setHeader(request);
|
||||
String result;
|
||||
try {
|
||||
HttpResponse response = httpclient.execute(request, localContext);
|
||||
result = responseProc(response);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
request.reset();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String appendGlobalParam(String url, Object param) {
|
||||
for (Map.Entry<String, Map<String, String>> stringMapEntry : globalParam.entrySet()) {
|
||||
if (url.startsWith(stringMapEntry.getKey())) {
|
||||
for (Map.Entry<String, String> paramEntry : stringMapEntry.getValue().entrySet()) {
|
||||
logger.debug("HTTP处理过程发送了参数:" + paramEntry.getKey() + "|" + paramEntry.getValue());
|
||||
if (param instanceof List)
|
||||
((List) param).add(new BasicNameValuePair(paramEntry.getKey(), paramEntry.getValue()));
|
||||
else
|
||||
url += "&" + paramEntry.getKey() + "=" + paramEntry.getValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送一个HTTP协议的POST请求
|
||||
*
|
||||
* @param url
|
||||
* @param param
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static String sendPostHttp(String url, Map<String, Object> param, boolean postTxtBody)
|
||||
throws RuntimeException {
|
||||
HttpContext localContext = new BasicHttpContext();
|
||||
setCookie(localContext, url);
|
||||
// logger.debug("远程URL:{}", url);
|
||||
HttpPost request = new HttpPost(url);
|
||||
List<NameValuePair> parm = new ArrayList<NameValuePair>();
|
||||
if (null != param && !param.isEmpty())
|
||||
for (Map.Entry<String, Object> paramEntity : param.entrySet()) {
|
||||
Object value = paramEntity.getValue();
|
||||
if (null != value && !StringUtils.isBlank(value.toString())) {
|
||||
logger.debug("HTTP处理过程发送了参数:" + paramEntity.getKey() + "|" + value);
|
||||
parm.add(new BasicNameValuePair(paramEntity.getKey(), value.toString()));
|
||||
}
|
||||
}
|
||||
appendGlobalParam(url, parm);
|
||||
HttpResponse response;
|
||||
try {
|
||||
request.setEntity(generyEntity(parm, "UTF-8", postTxtBody));
|
||||
setHeader(request);
|
||||
response = httpclient.execute(request, localContext);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
String result;
|
||||
try {
|
||||
result = responseProc(response);
|
||||
} catch (IOException e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
request.reset();
|
||||
}
|
||||
logger.debug("return is:" + result);
|
||||
return result;
|
||||
}
|
||||
|
||||
static Pattern urlPrePat = Pattern.compile("https?://([^/]*)?/?");
|
||||
|
||||
private static String getUrlPerfix(String url) {
|
||||
Matcher mat = urlPrePat.matcher(url);
|
||||
if (mat.find())
|
||||
return mat.group(1);
|
||||
return "";
|
||||
}
|
||||
|
||||
private static void setCookie(HttpContext localContext, String url) {
|
||||
String urlPrefix = getUrlPerfix(url);
|
||||
CookieStore cookieStore = new BasicCookieStore();
|
||||
List<Cookie> cookieList = cookiesMap.get(urlPrefix);
|
||||
if (cookieList != null && cookieList.size() > 0) {
|
||||
for (Cookie cookie : cookiesMap.get(urlPrefix)) {
|
||||
cookieStore.addCookie(cookie);
|
||||
}
|
||||
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
|
||||
}
|
||||
}
|
||||
|
||||
private static void parseCookie(HttpClientContext context, String url) {
|
||||
List<Cookie> cookies = context.getCookieStore().getCookies();
|
||||
String urlPrefix = getUrlPerfix(url);
|
||||
List<Cookie> oldCookies = cookiesMap.get(urlPrefix);
|
||||
if (oldCookies != null) {
|
||||
for (Cookie cookie : cookies) {
|
||||
for (Cookie oldCookie : oldCookies) {
|
||||
if (cookie.getName().equals(oldCookie.getName())) {
|
||||
oldCookies.remove(oldCookie);
|
||||
oldCookies.add(cookie);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else
|
||||
cookiesMap.put(urlPrefix, cookies);
|
||||
}
|
||||
|
||||
private static String responseProc(HttpResponse response) throws IOException {
|
||||
switch (response.getStatusLine().getStatusCode()) {
|
||||
case 200: {
|
||||
HttpEntity entity = response.getEntity();
|
||||
return EntityUtils.toString(entity, "UTF-8");
|
||||
}
|
||||
case 302: {
|
||||
return sendGetHttp(response.getFirstHeader("location").getValue(), "");
|
||||
}
|
||||
case 303:
|
||||
case 304: {
|
||||
Header[] headers = response.getAllHeaders();
|
||||
for (Header header : headers) {
|
||||
logger.debug(header.getName() + " : " + header.getValue());
|
||||
}
|
||||
}
|
||||
default:
|
||||
throw new HttpResponseException(response.getStatusLine().getStatusCode(),
|
||||
response.getStatusLine().getReasonPhrase());
|
||||
}
|
||||
}
|
||||
|
||||
public static void setHeader(HttpRequestBase request) {
|
||||
for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
|
||||
request.setHeader(headerEntry.getKey(), headerEntry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
public static HttpEntity generyEntity(List<NameValuePair> parm, String encode, boolean postTxtBody)
|
||||
throws Exception {
|
||||
if (postTxtBody && parm.size() > 0) {
|
||||
JSONObject paramJson = new JSONObject();
|
||||
for (NameValuePair nameValuePair : parm) {
|
||||
paramJson.put(nameValuePair.getName(), nameValuePair.getValue());
|
||||
}
|
||||
return (new StringEntity(paramJson.toString(), encode));
|
||||
} else
|
||||
return (new UrlEncodedFormEntity(parm, encode));
|
||||
}
|
||||
|
||||
// public static void main(String[] args) {
|
||||
// byte[] bytes = new byte[1];
|
||||
// if (bytes instanceof byte[]) {
|
||||
// System.out.println(1);
|
||||
// }
|
||||
// }
|
||||
}
|
||||
5
comm/Kernel/src/kernel/http/HttpMethodType.java
Executable file
5
comm/Kernel/src/kernel/http/HttpMethodType.java
Executable file
@@ -0,0 +1,5 @@
|
||||
package kernel.http;
|
||||
|
||||
public enum HttpMethodType {
|
||||
GET, POST, FILE
|
||||
}
|
||||
340
comm/Kernel/src/kernel/imagecode/ImageCodeServlet.java
Executable file
340
comm/Kernel/src/kernel/imagecode/ImageCodeServlet.java
Executable file
@@ -0,0 +1,340 @@
|
||||
package kernel.imagecode;
|
||||
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
import java.awt.Graphics;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.font.FontRenderContext;
|
||||
import java.awt.font.TextLayout;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Random;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.http.HttpServlet;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
|
||||
/**
|
||||
* 生成随机图片 <img src="image/verifycode.gif" id="veri"/>
|
||||
|
||||
*/
|
||||
public class ImageCodeServlet extends HttpServlet {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private Random random = new Random();// 随机器
|
||||
|
||||
|
||||
private static char[] captchars = new char[] { '2', '3', '4', '5', '6',
|
||||
'7', '8', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm',
|
||||
'n', 'p', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'A', 'B', 'C',
|
||||
'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S',
|
||||
'T', 'U', 'V', 'W', 'X', 'Y' };// 0,1,2易和字母的o,l,z易混淆,不生成,可以生成汉字
|
||||
// 设置备选汉字,剔除一些不雅的汉字
|
||||
private String base = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6";
|
||||
|
||||
public void doGet(HttpServletRequest req, HttpServletResponse resp)
|
||||
throws ServletException, IOException {
|
||||
|
||||
//修改的信息在此
|
||||
int num = 4;// 字符的多少
|
||||
int ImageWidth = num * 25;//图片的宽
|
||||
int ImageHeight = 40;//图片的高
|
||||
int line_left = 7;//从左上到右下的线条个数
|
||||
int line_right = 8;//从右上到左下的线条个数
|
||||
|
||||
int car = captchars.length - 1;
|
||||
Font font = getFont();// 获得写的时候的字体
|
||||
|
||||
// 随机写字母或汉字
|
||||
String test = "";
|
||||
/* if ((random.nextInt(2)) == 0) {
|
||||
for (int i = 0; i < num; i++) {
|
||||
// 1.随机得到num个字母或数字
|
||||
test += captchars[random.nextInt(car) + 1];
|
||||
font = new Font("Fixedsys", Font.PLAIN, 40);
|
||||
}
|
||||
} else {
|
||||
for (int i = 0; i < num; i++) {
|
||||
// 2.随机得到num个汉字
|
||||
// test += this.getRandomChar();
|
||||
// 3.第二种获得汉字常用方法,一般用这种
|
||||
int start = random.nextInt(base.length());
|
||||
test += base.substring(start, start + 1);
|
||||
font = new Font("Fixedsys", Font.BOLD, 28);
|
||||
}
|
||||
}*/ // update by Tony 2013-7-30 不生产汉字验证码
|
||||
for (int i = 0; i < num; i++) {
|
||||
// 1.随机得到num个字母或数字
|
||||
test += captchars[random.nextInt(car) + 1];
|
||||
font = new Font("Fixedsys", Font.PLAIN, 10); // Tony : 40
|
||||
}
|
||||
if(req.getSession().getAttribute("image_code_session")==null)req.getSession().removeAttribute("image_code_session");
|
||||
req.getSession().setAttribute("image_code_session", test);// 将字符串写入session
|
||||
|
||||
//JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(resp.getOutputStream());// 得到输出流
|
||||
|
||||
BufferedImage bi = new BufferedImage(ImageWidth, ImageHeight,
|
||||
BufferedImage.TYPE_BYTE_INDEXED);
|
||||
|
||||
Graphics2D graphics = bi.createGraphics();
|
||||
|
||||
Color c = getRandColor(200, 250);
|
||||
graphics.setColor(c);// 设置背景色
|
||||
|
||||
graphics.fillRect(0, 0, bi.getWidth(), bi.getHeight());
|
||||
|
||||
graphics.setColor(Color.black);
|
||||
|
||||
graphics.setFont(font);
|
||||
graphics.setColor(this.getRandColor());
|
||||
//graphics.drawString(test, 10, 50);// 将字写到图片上
|
||||
// graphics.drawString(test, 5, 25);// 将字写到图片上
|
||||
|
||||
// TextLayout textTl = new TextLayout(test, new Font("Fixedsys",
|
||||
// Font.PLAIN, 20), new FontRenderContext(null, true, false));// 获得字体一样的字,20是字体的大小
|
||||
TextLayout textTl = new TextLayout(test, new Font("Fixedsys",
|
||||
Font.PLAIN, 25), new FontRenderContext(null, true, false));// 获得字体一样的字,20是字体的大小
|
||||
// textTl.draw(graphics, 30, 60);// 对字体加投影,第二个是左右相距,越大越远,第三个参数是上下两层相距距离,越大越近
|
||||
textTl.draw(graphics, 20, 35);// 对字体加投影,第二个是左右相距,越大越远,第三个参数是上下两层相距距离,越大越近
|
||||
|
||||
int w = bi.getWidth();
|
||||
int h = bi.getHeight();
|
||||
shear(graphics, w, h, c);// 使图片扭曲
|
||||
|
||||
this.drawThickLine(graphics, 0, random.nextInt(ImageHeight) + 1,
|
||||
ImageWidth, random.nextInt(ImageHeight) + 1, 4, getRandColor(
|
||||
100, 200));// 加一道线
|
||||
|
||||
// 从左上到右下加上多道干扰线
|
||||
graphics.setColor(getRandColor(160, 200));// 设置线条的颜色
|
||||
for (int i = 0; i < line_left; i++) {
|
||||
int x = random.nextInt(ImageWidth - 1);
|
||||
int y = random.nextInt(ImageHeight - 1);
|
||||
int xl = random.nextInt(6) + 1;
|
||||
int yl = random.nextInt(12) + 1;
|
||||
graphics.drawLine(x, y, x + xl + 40, y + yl + 20);
|
||||
}
|
||||
// 从右上到左下加多道干扰线
|
||||
for (int i = 0; i < line_right; i++) {
|
||||
int x = random.nextInt(ImageWidth - 1);
|
||||
int y = random.nextInt(ImageHeight - 1);
|
||||
int xl = random.nextInt(12) + 1;
|
||||
int yl = random.nextInt(6) + 1;
|
||||
graphics.drawLine(x, y, x - xl + 40, y - yl);
|
||||
}
|
||||
// 添加噪点
|
||||
// float yawpRate = 0.012f;// 噪声率
|
||||
// int area = (int) (yawpRate * w * h);
|
||||
// for (int i = 0; i < area; i++) {
|
||||
// int x = random.nextInt(w);
|
||||
// int y = random.nextInt(h);
|
||||
// int rgb = getRandomIntColor();
|
||||
// bi.setRGB(x, y, rgb);
|
||||
// }
|
||||
|
||||
// 设置图片类型
|
||||
resp.setContentType("image/jpg");
|
||||
// 写出
|
||||
// encoder.encode(bi);
|
||||
ImageIO.write(bi, "JPEG", resp.getOutputStream());
|
||||
|
||||
}
|
||||
|
||||
// 添加噪点的方法
|
||||
private int getRandomIntColor() {
|
||||
int[] rgb = this.getRandomRgb();
|
||||
int color = 0;
|
||||
for (int c : rgb) {
|
||||
color = color << 8;
|
||||
color = color | c;
|
||||
}
|
||||
return color;
|
||||
}
|
||||
|
||||
private int[] getRandomRgb() {
|
||||
int[] rgb = new int[3];
|
||||
for (int i = 0; i < 3; i++) {
|
||||
rgb[i] = random.nextInt(255);
|
||||
}
|
||||
return rgb;
|
||||
}
|
||||
|
||||
// 扭曲方法
|
||||
private void shear(Graphics g, int w1, int h1, Color color) {
|
||||
shearX(g, w1, h1, color);
|
||||
shearY(g, w1, h1, color);
|
||||
}
|
||||
|
||||
private void shearX(Graphics g, int w1, int h1, Color color) {
|
||||
|
||||
int period = random.nextInt(2);
|
||||
|
||||
boolean borderGap = true;
|
||||
int frames = 1;
|
||||
int phase = random.nextInt(2);
|
||||
|
||||
for (int i = 0; i < h1; i++) {
|
||||
double d = (double) (period >> 1)
|
||||
* Math.sin((double) i / (double) period
|
||||
+ (6.2831853071795862D * (double) phase)
|
||||
/ (double) frames);
|
||||
g.copyArea(0, i, w1, 1, (int) d, 0);
|
||||
if (borderGap) {
|
||||
g.setColor(color);
|
||||
g.drawLine((int) d, i, 0, i);
|
||||
g.drawLine((int) d + w1, i, w1, i);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void shearY(Graphics g, int w1, int h1, Color color) {
|
||||
|
||||
int period = random.nextInt(40) + 10; // 50;
|
||||
|
||||
boolean borderGap = true;
|
||||
int frames = 20;
|
||||
int phase = 7;
|
||||
for (int i = 0; i < w1; i++) {
|
||||
double d = (double) (period >> 1)
|
||||
* Math.sin((double) i / (double) period
|
||||
+ (6.2831853071795862D * (double) phase)
|
||||
/ (double) frames);
|
||||
g.copyArea(i, 0, 1, h1, 0, (int) d);
|
||||
if (borderGap) {
|
||||
g.setColor(color);
|
||||
g.drawLine(i, (int) d, i, 0);
|
||||
g.drawLine(i, (int) d + h1, i, h1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 画一道粗线的方法
|
||||
private void drawThickLine(Graphics g, int x1, int y1, int x2, int y2,
|
||||
int thickness, Color c) {
|
||||
|
||||
// The thick line is in fact a filled polygon
|
||||
g.setColor(c);
|
||||
int dX = x2 - x1;
|
||||
int dY = y2 - y1;
|
||||
// line length
|
||||
double lineLength = Math.sqrt(dX * dX + dY * dY);
|
||||
|
||||
double scale = (double) (thickness) / (2 * lineLength);
|
||||
|
||||
// The x and y increments from an endpoint needed to create a
|
||||
// rectangle...
|
||||
double ddx = -scale * (double) dY;
|
||||
double ddy = scale * (double) dX;
|
||||
ddx += (ddx > 0) ? 0.5 : -0.5;
|
||||
ddy += (ddy > 0) ? 0.5 : -0.5;
|
||||
int dx = (int) ddx;
|
||||
int dy = (int) ddy;
|
||||
|
||||
// Now we can compute the corner points...
|
||||
int xPoints[] = new int[4];
|
||||
int yPoints[] = new int[4];
|
||||
|
||||
xPoints[0] = x1 + dx;
|
||||
yPoints[0] = y1 + dy;
|
||||
xPoints[1] = x1 - dx;
|
||||
yPoints[1] = y1 - dy;
|
||||
xPoints[2] = x2 - dx;
|
||||
yPoints[2] = y2 - dy;
|
||||
xPoints[3] = x2 + dx;
|
||||
yPoints[3] = y2 + dy;
|
||||
|
||||
g.fillPolygon(xPoints, yPoints, 4);
|
||||
}
|
||||
|
||||
// 随机得到一个汉字的方法
|
||||
protected char getRandomChar() {
|
||||
final int minFirstByte = 176;
|
||||
final int maxFirstByte = 215;
|
||||
final int minSecondByte = 161;
|
||||
final int maxSecondByte = 249;
|
||||
|
||||
byte[] b = new byte[2];
|
||||
b[0] = (byte) (getRandomIntBetween(minFirstByte, maxFirstByte));
|
||||
b[1] = (byte) (getRandomIntBetween(minSecondByte, maxSecondByte));
|
||||
try {
|
||||
String s = new String(b, "gb2312");
|
||||
assert s.length() == 1;
|
||||
return s.charAt(0);
|
||||
} catch (UnsupportedEncodingException uee) {
|
||||
// 重试
|
||||
return getRandomChar();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取两个整数之间的某个随机数,包含较小的整数,不包含较大的整数
|
||||
*/
|
||||
private int getRandomIntBetween(int first, int second) {
|
||||
if (second < first) {
|
||||
int tmp = first;
|
||||
first = second;
|
||||
second = tmp;
|
||||
}
|
||||
return random.nextInt(second - first) + first;
|
||||
}
|
||||
|
||||
/**
|
||||
* 产生随机字体
|
||||
*/
|
||||
private Font getFont() {
|
||||
Random random = new Random();
|
||||
Font font[] = new Font[5];
|
||||
font[0] = new Font("Ravie", Font.PLAIN, 40);
|
||||
font[1] = new Font("Antique Olive Compact", Font.PLAIN, 40);
|
||||
font[2] = new Font("Fixedsys", Font.PLAIN, 40);
|
||||
font[3] = new Font("Wide Latin", Font.PLAIN, 40);
|
||||
font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, 40);
|
||||
return font[random.nextInt(5)];
|
||||
}
|
||||
/**
|
||||
* 产生随机字体
|
||||
*/
|
||||
private Font getFont_Old() {
|
||||
Random random = new Random();
|
||||
Font font[] = new Font[5];
|
||||
font[0] = new Font("Ravie", Font.PLAIN, 40);
|
||||
font[1] = new Font("Antique Olive Compact", Font.PLAIN, 40);
|
||||
font[2] = new Font("Fixedsys", Font.PLAIN, 40);
|
||||
font[3] = new Font("Wide Latin", Font.PLAIN, 40);
|
||||
font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, 40);
|
||||
return font[random.nextInt(5)];
|
||||
}
|
||||
/**
|
||||
* 随机产生定义的颜色
|
||||
*/
|
||||
private Color getRandColor() {
|
||||
Random random = new Random();
|
||||
Color color[] = new Color[10];
|
||||
color[0] = new Color(32, 158, 25);
|
||||
color[1] = new Color(218, 42, 19);
|
||||
color[2] = new Color(31, 75, 208);
|
||||
return color[random.nextInt(3)];
|
||||
}
|
||||
|
||||
private Color getRandColor(int fc, int bc) {
|
||||
if (fc > 255)
|
||||
fc = 255;
|
||||
if (bc > 255)
|
||||
bc = 255;
|
||||
int r = fc + random.nextInt(bc - fc);
|
||||
int g = fc + random.nextInt(bc - fc);
|
||||
int b = fc + random.nextInt(bc - fc);
|
||||
return new Color(r, g, b);
|
||||
}
|
||||
}
|
||||
17
comm/Kernel/src/kernel/service/TransactionMethodFragmentFun.java
Executable file
17
comm/Kernel/src/kernel/service/TransactionMethodFragmentFun.java
Executable file
@@ -0,0 +1,17 @@
|
||||
package kernel.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import util.concurrent.gofun.core.FunParams;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
@Service
|
||||
public class TransactionMethodFragmentFun {
|
||||
// 不能有这个注解
|
||||
//@Transactional(propagation = Propagation.REQUIRED)
|
||||
public FunParams runInTransaction(FunParams inputParams, Function<FunParams, FunParams> fun) {
|
||||
return fun.apply(inputParams);
|
||||
}
|
||||
}
|
||||
4
comm/Kernel/src/kernel/service/TwoDimensionCodeContentService.java
Executable file
4
comm/Kernel/src/kernel/service/TwoDimensionCodeContentService.java
Executable file
@@ -0,0 +1,4 @@
|
||||
package kernel.service;
|
||||
public interface TwoDimensionCodeContentService {
|
||||
public String encoder(String content);
|
||||
}
|
||||
45
comm/Kernel/src/kernel/service/TwoDimensionCodeContentServiceImpl.java
Executable file
45
comm/Kernel/src/kernel/service/TwoDimensionCodeContentServiceImpl.java
Executable file
@@ -0,0 +1,45 @@
|
||||
package kernel.service;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.zxing.BarcodeFormat;
|
||||
import com.google.zxing.EncodeHintType;
|
||||
import com.google.zxing.MultiFormatWriter;
|
||||
import com.google.zxing.client.j2se.MatrixToImageWriter;
|
||||
import com.google.zxing.common.BitMatrix;
|
||||
|
||||
import util.DateUtil;
|
||||
import util.RandomUtil;
|
||||
|
||||
public class TwoDimensionCodeContentServiceImpl implements TwoDimensionCodeContentService {
|
||||
private String imgPath;
|
||||
@Override
|
||||
public String encoder(String content) {
|
||||
String imagename = "/" + DateUtil.getToday("yyMMddHHmmss") + RandomUtil.getRandomNum(8) + ".png"; // 生成二维码图片相对
|
||||
// 地址和名称
|
||||
String pathname = imgPath + imagename; // 生成二维码图片存放的地址和名称
|
||||
|
||||
File file = new File(pathname);
|
||||
int width = 691; // 图像宽度
|
||||
int height = 691; // 图像高度
|
||||
String format = "png";// 图像类型
|
||||
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
|
||||
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
|
||||
BitMatrix bitMatrix;
|
||||
try {
|
||||
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
|
||||
MatrixToImageWriter.writeToFile(bitMatrix, format, file);// 输出图像
|
||||
} catch (Exception e) {
|
||||
|
||||
e.printStackTrace();
|
||||
} // 生成矩阵
|
||||
|
||||
return imagename;
|
||||
}
|
||||
|
||||
public void setImgPath(String imgPath) {
|
||||
this.imgPath = imgPath;
|
||||
}
|
||||
}
|
||||
10
comm/Kernel/src/kernel/sessiontoken/SessionTokenService.java
Executable file
10
comm/Kernel/src/kernel/sessiontoken/SessionTokenService.java
Executable file
@@ -0,0 +1,10 @@
|
||||
package kernel.sessiontoken;
|
||||
|
||||
public interface SessionTokenService {
|
||||
|
||||
public String savePut(String partyId);
|
||||
|
||||
public String cacheGet(String session_token);
|
||||
|
||||
public void delete(String session_token);
|
||||
}
|
||||
35
comm/Kernel/src/kernel/sessiontoken/internal/SessionTokenServiceImpl.java
Executable file
35
comm/Kernel/src/kernel/sessiontoken/internal/SessionTokenServiceImpl.java
Executable file
@@ -0,0 +1,35 @@
|
||||
package kernel.sessiontoken.internal;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import kernel.sessiontoken.SessionTokenService;
|
||||
import kernel.util.StringUtils;
|
||||
import kernel.util.UUIDGenerator;
|
||||
|
||||
public class SessionTokenServiceImpl implements SessionTokenService {
|
||||
|
||||
private volatile Map<String, String> cache = new ConcurrentHashMap<String, String>();
|
||||
|
||||
public String savePut(String partyId) {
|
||||
String session_token = UUIDGenerator.getUUID();
|
||||
cache.put(session_token, partyId);
|
||||
return session_token;
|
||||
}
|
||||
|
||||
public String cacheGet(String session_token) {
|
||||
if (StringUtils.isNullOrEmpty(session_token)) {
|
||||
return null;
|
||||
}
|
||||
return cache.get(session_token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String session_token) {
|
||||
if (StringUtils.isNullOrEmpty(session_token)) {
|
||||
return;
|
||||
}
|
||||
cache.remove(session_token);
|
||||
}
|
||||
|
||||
}
|
||||
76
comm/Kernel/src/kernel/springframework/ServiceLocator.java
Executable file
76
comm/Kernel/src/kernel/springframework/ServiceLocator.java
Executable file
@@ -0,0 +1,76 @@
|
||||
package kernel.springframework;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
|
||||
public class ServiceLocator {
|
||||
/**
|
||||
* spring应用上下文
|
||||
*/
|
||||
private static ApplicationContext CONTEXT;
|
||||
|
||||
/**
|
||||
* Method getApplicationContext.
|
||||
*
|
||||
* @return ApplicationContext
|
||||
*/
|
||||
public static ApplicationContext getApplicationContext() {
|
||||
if (CONTEXT == null) {
|
||||
CONTEXT = new ClassPathXmlApplicationContext(
|
||||
new String[] { "classpath*:spring/*.xml" });
|
||||
}
|
||||
return CONTEXT;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Method setApplicationContext.
|
||||
*
|
||||
* @param outcontext ApplicationContext
|
||||
*/
|
||||
public static void setApplicationContext(ApplicationContext outcontext) {
|
||||
CONTEXT = outcontext;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个Spring的Bean对象
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static Object getBean(String name) {
|
||||
return getApplicationContext().getBean(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过calss 获得一个Spring的Bean对象
|
||||
*
|
||||
* @param T
|
||||
* @return
|
||||
*/
|
||||
public static <T> T getBean(Class<T> T) {
|
||||
return getApplicationContext().getBean(T);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key :properties定义的值
|
||||
* @param defaultMessage:取不到值,默认的值
|
||||
* @return
|
||||
*/
|
||||
public static String getMessage(String key,String defaultMessage){
|
||||
return CONTEXT.getMessage(key, null, defaultMessage,null);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param key :properties定义的值
|
||||
* @return 如果key值 没有,将返回"",
|
||||
*/
|
||||
public static String getMessage(String key){
|
||||
return CONTEXT.getMessage(key, null,"",null);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package kernel.springframework.web.context;
|
||||
|
||||
import javax.servlet.ServletContextEvent;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.web.context.ContextLoaderListener;
|
||||
import org.springframework.web.context.support.WebApplicationContextUtils;
|
||||
|
||||
import kernel.springframework.ServiceLocator;
|
||||
|
||||
|
||||
public class ApplicationContextUtilsInitListener extends ContextLoaderListener {
|
||||
|
||||
private Logger logger = LogManager.getLogger(ApplicationContextUtilsInitListener.class);
|
||||
/**
|
||||
* Method contextInitialized.
|
||||
*
|
||||
* @param event
|
||||
* ServletContextEvent
|
||||
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
|
||||
*/
|
||||
public void contextInitialized(ServletContextEvent event) {
|
||||
super.contextInitialized(event);
|
||||
ApplicationContext context = WebApplicationContextUtils
|
||||
.getWebApplicationContext(event.getServletContext());
|
||||
ServiceLocator.setApplicationContext(context);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void contextDestroyed(ServletContextEvent event) {
|
||||
super.contextDestroyed(event);
|
||||
logger.info("--销毁");
|
||||
}
|
||||
}
|
||||
124
comm/Kernel/src/kernel/util/Arith.java
Executable file
124
comm/Kernel/src/kernel/util/Arith.java
Executable file
@@ -0,0 +1,124 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class Arith{
|
||||
//默认除法运算精度
|
||||
private static final int DEF_DIV_SCALE = 10;
|
||||
//这个类不能实例化
|
||||
private Arith(){
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供精确的加法运算。
|
||||
* @param v1 被加数
|
||||
* @param v2 加数
|
||||
* @return 两个参数的和
|
||||
*/
|
||||
public static double add(double v1,double v2){
|
||||
BigDecimal b1 = new BigDecimal(Double.toString(v1));
|
||||
BigDecimal b2 = new BigDecimal(Double.toString(v2));
|
||||
return b1.add(b2).doubleValue();
|
||||
}
|
||||
/**
|
||||
* 提供精确的减法运算。
|
||||
* @param v1 被减数
|
||||
* @param v2 减数
|
||||
* @return 两个参数的差
|
||||
*/
|
||||
public static double sub(double v1,double v2){
|
||||
BigDecimal b1 = new BigDecimal(Double.toString(v1));
|
||||
BigDecimal b2 = new BigDecimal(Double.toString(v2));
|
||||
return b1.subtract(b2).doubleValue();
|
||||
}
|
||||
/**
|
||||
* 提供精确的乘法运算。
|
||||
* @param v1 被乘数
|
||||
* @param v2 乘数
|
||||
* @return 两个参数的积
|
||||
*/
|
||||
public static double mul(double v1,double v2){
|
||||
BigDecimal b1 = new BigDecimal(Double.toString(v1));
|
||||
BigDecimal b2 = new BigDecimal(Double.toString(v2));
|
||||
return b1.multiply(b2).doubleValue();
|
||||
}
|
||||
|
||||
public static double mul(double v1,double v2, int scale){
|
||||
BigDecimal b1 = new BigDecimal(v1);
|
||||
BigDecimal b2 = new BigDecimal(v2);
|
||||
BigDecimal multiply = b1.multiply(b2);
|
||||
if (null == multiply || multiply.compareTo(new BigDecimal("0.00")) == 0){
|
||||
return 0.0D;
|
||||
}
|
||||
return multiply.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
|
||||
* 小数点以后10位,以后的数字四舍五入。
|
||||
* @param v1 被除数
|
||||
* @param v2 除数
|
||||
* @return 两个参数的商
|
||||
*/
|
||||
public static double div(double v1,double v2){
|
||||
return div(v1,v2,DEF_DIV_SCALE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
|
||||
* 定精度,以后的数字四舍五入。
|
||||
* @param v1 被除数
|
||||
* @param v2 除数
|
||||
* @param scale 表示表示需要精确到小数点以后几位。
|
||||
* @return 两个参数的商
|
||||
*/
|
||||
public static double div(double v1,double v2,int scale){
|
||||
if(scale<0){
|
||||
throw new IllegalArgumentException(
|
||||
"The scale must be a positive integer or zero");
|
||||
}
|
||||
BigDecimal b1 = new BigDecimal(Double.toString(v1));
|
||||
BigDecimal b2 = new BigDecimal(Double.toString(v2));
|
||||
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供精确的小数位四舍五入处理。
|
||||
* @param v 需要四舍五入的数字
|
||||
* @param scale 小数点后保留几位
|
||||
* @return 四舍五入后的结果
|
||||
*/
|
||||
public static double round(double v,int scale){
|
||||
|
||||
if(scale<0){
|
||||
throw new IllegalArgumentException(
|
||||
"The scale must be a positive integer or zero");
|
||||
}
|
||||
BigDecimal b = new BigDecimal(Double.toString(v));
|
||||
BigDecimal one = new BigDecimal("1");
|
||||
return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供精确的小数位直接舍去操作
|
||||
* @param v 需要直接舍去的double类型数字
|
||||
* @param scale 小数点后保留几位
|
||||
* @return 舍去后的结果
|
||||
*/
|
||||
public static double roundDown(double v,int scale){
|
||||
|
||||
if (scale < 0) {
|
||||
throw new IllegalArgumentException(
|
||||
"The scale must be a positive integer or zero");
|
||||
}
|
||||
BigDecimal b = new BigDecimal(Double.toString(v));
|
||||
BigDecimal one = new BigDecimal("1");
|
||||
return b.divide(one,scale,BigDecimal.ROUND_DOWN).doubleValue();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(roundDown(1.759d,2));
|
||||
System.out.println("mul(3.15d,3.12,2) = " + mul(3.15d, 3.12, 2));
|
||||
System.out.println("roundDown(mul(3.15,3.12),2) = " + roundDown(mul(3.15, 3.12), 2));
|
||||
}
|
||||
}
|
||||
711
comm/Kernel/src/kernel/util/ByteUtils.java
Executable file
711
comm/Kernel/src/kernel/util/ByteUtils.java
Executable file
@@ -0,0 +1,711 @@
|
||||
package kernel.util;
|
||||
|
||||
/**
|
||||
|
||||
* 一些字节处理的工具函数,用于一些比较底层的基于字节的协议转换
|
||||
|
||||
*/
|
||||
public abstract class ByteUtils {
|
||||
|
||||
/**
|
||||
* 初始化内存字节
|
||||
*
|
||||
* @param src
|
||||
* byte[]
|
||||
* @param c
|
||||
* byte
|
||||
* @param pos
|
||||
* int
|
||||
* @param count
|
||||
* int
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] memset(byte[] src, byte c, int pos, int count) {
|
||||
if (src == null)
|
||||
return src;
|
||||
|
||||
if (pos < 0 || pos > src.length || count <= 0) {
|
||||
return src;
|
||||
}
|
||||
|
||||
for (int i = 0; i < count && pos + i < src.length; i++) {
|
||||
src[pos + i] = c;
|
||||
}
|
||||
|
||||
return src;
|
||||
}
|
||||
|
||||
/**
|
||||
* 内存字节拷贝
|
||||
*
|
||||
* @param dest
|
||||
* byte[]
|
||||
* @param pos
|
||||
* int
|
||||
* @param src
|
||||
* byte[]
|
||||
* @param size
|
||||
* int
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] memcpy(byte[] dest, int pos, byte[] src, int size) {
|
||||
if (size >= 0) {
|
||||
size = size > dest.length ? dest.length : size;
|
||||
System.arraycopy(src, 0, dest, pos, size);
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字节头部填充
|
||||
*
|
||||
* @param src
|
||||
* byte[]
|
||||
* @param length
|
||||
* int
|
||||
* @param fill
|
||||
* byte
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] fillHead(byte[] src, int length, byte fill) {
|
||||
if (src.length >= length) {
|
||||
return src;
|
||||
}
|
||||
|
||||
byte[] dest = new byte[length];
|
||||
ByteUtils.memset(dest, fill, 0, length);
|
||||
ByteUtils.memcpy(dest, length > src.length ? length - src.length : 0,
|
||||
src, src.length);
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字节尾部填充
|
||||
*
|
||||
* @param src
|
||||
* byte[]
|
||||
* @param length
|
||||
* int
|
||||
* @param fill
|
||||
* byte
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] fillTail(byte[] src, int length, byte fill) {
|
||||
if (src.length >= length) {
|
||||
return src;
|
||||
}
|
||||
|
||||
byte[] dest = new byte[length];
|
||||
ByteUtils.memset(dest, fill, 0, length);
|
||||
ByteUtils.memcpy(dest, 0, src, src.length);
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入字节到目标字节数组,使用者须保证目标空间足够,后面的字节被覆盖
|
||||
*
|
||||
* @param dest
|
||||
* byte[]
|
||||
* @param src
|
||||
* byte[]
|
||||
* @param pos
|
||||
* int
|
||||
* @param length
|
||||
* int
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] insert(byte[] dest, byte[] src, int pos, int length) {
|
||||
if (length > dest.length) {
|
||||
length = dest.length;
|
||||
}
|
||||
|
||||
for (int i = 0; i < pos + length; i++) {
|
||||
if (i >= pos && i < pos + length) {
|
||||
if (i + length < dest.length) {
|
||||
dest[i + length] = dest[i];
|
||||
}
|
||||
if (i - pos < src.length) {
|
||||
dest[i] = src[i - pos];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制字节到目标字节数组,使用者须保证目标空间足够
|
||||
*
|
||||
* @param dest
|
||||
* byte[]
|
||||
* @param src
|
||||
* byte[]
|
||||
* @param pos
|
||||
* int
|
||||
* @param length
|
||||
* int
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] copyto(byte[] dest, byte[] src, int pos, int length) {
|
||||
if (length > src.length) {
|
||||
length = src.length;
|
||||
}
|
||||
|
||||
if (dest == null || dest.length < pos + length) {
|
||||
byte[] buf = new byte[pos + length];
|
||||
memcpy(buf, 0, dest, pos);
|
||||
dest = buf;
|
||||
}
|
||||
|
||||
for (int i = 0; i < length; i++) {
|
||||
dest[pos + i] = src[i];
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从源字节数组指定位置复制字节到目标字节数组,使用者须保证目标空间足够
|
||||
*
|
||||
* @param dest
|
||||
* byte[]
|
||||
* @param src
|
||||
* byte[]
|
||||
* @param pos
|
||||
* int
|
||||
* @param length
|
||||
* int
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] copyfrom(byte[] dest, byte[] src, int pos, int length) {
|
||||
if (length > src.length) {
|
||||
length = src.length;
|
||||
}
|
||||
|
||||
if (dest == null || dest.length < length) { // 只能通过返回参数返回,无法通过入参返回,与C语言不同。
|
||||
dest = new byte[length];
|
||||
}
|
||||
|
||||
for (int i = 0; i < length; i++) {
|
||||
dest[i] = src[pos + i];
|
||||
}
|
||||
|
||||
return copy(dest, 0, length); // 返回一个新建数组
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除字节内容,返回删除后的内容
|
||||
*
|
||||
* @param src
|
||||
* byte[]
|
||||
* @param pos
|
||||
* int
|
||||
* @param length
|
||||
* int
|
||||
* @return byte[] 删除一些字节的新数组
|
||||
*/
|
||||
public static byte[] delete(byte src[], int pos, int length) {
|
||||
if (src == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (pos > src.length || pos < 0 || length < 0) { // 非法参数
|
||||
return src;
|
||||
}
|
||||
|
||||
if (pos + length > src.length) {
|
||||
length = src.length - pos;
|
||||
}
|
||||
|
||||
byte[] dest = new byte[src.length - length];
|
||||
for (int i = 0; i < src.length; i++) {
|
||||
if (i - pos >= 0 && i - pos < length) {
|
||||
continue;
|
||||
}
|
||||
dest[i] = src[i];
|
||||
}
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字节拷贝,返回拷贝内容
|
||||
*
|
||||
* @param src
|
||||
* byte[]
|
||||
* @param pos
|
||||
* int
|
||||
* @param size
|
||||
* int
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] copy(byte[] src, int pos, int size) {
|
||||
if (pos < 0 || pos > src.length || size <= 0) { // 非法参数
|
||||
return null;
|
||||
}
|
||||
|
||||
byte[] dest = new byte[src.length - pos < size ? src.length - pos
|
||||
: size];
|
||||
for (int i = 0; i < size && pos + i < src.length; i++) {
|
||||
dest[i] = src[pos + i];
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换成16进制的格式
|
||||
*
|
||||
* @param length
|
||||
* int
|
||||
* @param hexlen
|
||||
* int
|
||||
* @param fillhead
|
||||
* byte
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] toHexBytes(int length, int hexlen, byte fillhead) {
|
||||
if (hexlen <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
byte dest[] = new byte[hexlen];
|
||||
ByteUtils.memset(dest, fillhead, 0, hexlen);
|
||||
byte[] src = Integer.toHexString(length).getBytes();
|
||||
System.arraycopy(src, 0, dest, hexlen - src.length > 0 ? hexlen
|
||||
- src.length : 0, src.length);
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param b
|
||||
* byte[]
|
||||
* @return int
|
||||
*/
|
||||
public static int bytes2int(byte[] b) {
|
||||
// byte[] b=new byte[]{1,2,3,4};
|
||||
int mask = 0xff;
|
||||
int temp = 0;
|
||||
int res = 0;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
res <<= 8;
|
||||
temp = b[i] & mask;
|
||||
res |= temp;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param b
|
||||
* byte
|
||||
* @return String
|
||||
*/
|
||||
public static String byte2hex(byte b) {
|
||||
String hex = Integer.toHexString((int) b & 0xff);
|
||||
if (hex.length() == 1) {
|
||||
hex = "0" + hex;
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param hex
|
||||
* String
|
||||
* @return byte
|
||||
*/
|
||||
public static byte hex2byte(String hex) {
|
||||
return (byte) (Integer.parseInt(hex, 16) & 0xff);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param hex
|
||||
* String
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] hex2bytes(String hex) {
|
||||
if (hex == null || hex.trim().length() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
byte[] dest = new byte[hex.length() / 2];
|
||||
for (int i = 0; i < hex.length() / 2; i++) {
|
||||
String h = hex.substring(2 * i, 2 * i + 2);
|
||||
dest[i] = hex2byte(h);
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param bytes
|
||||
* byte[]
|
||||
* @return String
|
||||
*/
|
||||
public static String bytes2hex(byte[] bytes) {
|
||||
StringBuffer sb = null;
|
||||
if (bytes == null || bytes.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
sb = new StringBuffer();
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
sb.append(byte2hex(bytes[i]));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param num
|
||||
* int
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] int2bytes(int num) {
|
||||
byte[] b = new byte[4];
|
||||
// int mask=0xff;
|
||||
for (int i = 0; i < 4; i++) {
|
||||
b[i] = (byte) (num >>> (24 - i * 8));
|
||||
// System.out.print(Integer.toHexString((int)b[i]));
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param num
|
||||
* int
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] short2bytes(int num) {
|
||||
num &= 0xffff;
|
||||
byte[] b = new byte[2];
|
||||
// int mask=0xff;
|
||||
for (int i = 0; i < 2; i++) {
|
||||
b[i] = (byte) (num >>> (8 - i * 8));
|
||||
// System.out.print(Integer.toHexString((int)b[i]));
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
/**
|
||||
* byte2short
|
||||
*
|
||||
* @param len
|
||||
* byte[]
|
||||
* @return int
|
||||
*/
|
||||
// public static int byte2short(byte[] b) {
|
||||
// int mask = 0xff;
|
||||
// int temp = 0;
|
||||
// int res = 0;
|
||||
// for (int i = 0; i < 2; i++) {
|
||||
// res <<= 8;
|
||||
// temp = b[i] & mask;
|
||||
// res |= temp;
|
||||
// }
|
||||
// return res;
|
||||
// }
|
||||
public static int byte2short(byte[] b) {
|
||||
int mask = 0xff;
|
||||
int temp = 0;
|
||||
int res = 0;
|
||||
for (int i = 0; i < 2; i++) {
|
||||
res = ((res << 8) & 0xffff);
|
||||
temp = b[i] & mask;
|
||||
res |= temp;
|
||||
}
|
||||
return res & 0xffff;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param h
|
||||
* int
|
||||
* @return int
|
||||
*/
|
||||
public static int htonl(int h) {
|
||||
int nl = 0;
|
||||
int b = 0;
|
||||
|
||||
for (int i = 0; i < 4; i++) {
|
||||
b = (h << (24 - i * 8)) & 0xff000000;
|
||||
// System.out.println(Integer.toHexString(b));
|
||||
// System.out.println(Integer.toHexString(b >> (i * 8)));
|
||||
nl = nl + (b >> (i * 8));
|
||||
}
|
||||
|
||||
// /System.out.println(Integer.toHexString(nl));
|
||||
return nl;
|
||||
}
|
||||
|
||||
public static byte[] htonlbytes(int h) {
|
||||
// return int2bytes(htonl(h));
|
||||
return int2bytes(h);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param h
|
||||
* int
|
||||
* @return int
|
||||
*/
|
||||
public static int htons(int h) {
|
||||
int ns = 0;
|
||||
int b = 0;
|
||||
for (int i = 0; i < 2; i++) {
|
||||
b = (h << (8 - i * 8)) & 0xff00;
|
||||
// System.out.println(Integer.toHexString(b));
|
||||
// System.out.println(Integer.toHexString(b >> 8));
|
||||
ns = ns + (b >> (i * 8));
|
||||
}
|
||||
|
||||
// System.out.println(Integer.toHexString(ns));
|
||||
return ns;
|
||||
}
|
||||
|
||||
public static byte[] htonsbytes(int h) {
|
||||
// return short2bytes(htons(h));
|
||||
return short2bytes(h);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param n
|
||||
* int
|
||||
* @return int
|
||||
*/
|
||||
public static int ntohl(int n) {
|
||||
return htonl(n);
|
||||
}
|
||||
|
||||
public static int nbytestohl(byte[] n) {
|
||||
// return ntohl(bytes2int(n));
|
||||
return bytes2int(n);
|
||||
}
|
||||
|
||||
public static int ntohs(int n) {
|
||||
return htons(n);
|
||||
}
|
||||
|
||||
public static int nbytestohs(byte[] n) {
|
||||
// return ntohs(byte2short(n));
|
||||
return byte2short(n);
|
||||
}
|
||||
|
||||
// /**
|
||||
// * getZteIHLRChecksum
|
||||
// * @param msg char[]
|
||||
// * @return char[]
|
||||
// */
|
||||
// public static char[] getZteIHLRChecksum(char[] msg) {
|
||||
// int i = 0, j = 0;
|
||||
// char[] checksum = new char[4];
|
||||
//
|
||||
// for (i = 0; i < msg.length / 4; i++) {
|
||||
// for (j = 0; j < 4; j++) {
|
||||
// checksum[j] ^= msg[i * 4 + j];
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// for (j = 0; j < msg.length % 4; j++) {
|
||||
// checksum[j] ^= msg[i * 4 + j];
|
||||
// }
|
||||
//
|
||||
// for (i = 0; i < 4; i++) {
|
||||
// int k = ~checksum[i] & 0xff;
|
||||
// checksum[i] = (char) k;
|
||||
// }
|
||||
//
|
||||
// StringBuffer sb = new StringBuffer();
|
||||
// for (i = 0; i < 4; i++) {
|
||||
// String s = Integer.toHexString(checksum[i] & 0xff).toUpperCase();
|
||||
// if (s.length() < 2) {
|
||||
// sb.append("0").append(s);
|
||||
// }
|
||||
// else {
|
||||
// sb.append(s);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return sb.toString().toCharArray();
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * getZtePCSChecksum
|
||||
// * @param msg char[]
|
||||
// * @return char[]
|
||||
// */
|
||||
// public static char[] getZtePCSChecksum(char[] msg) {
|
||||
// int i = 0, j = 0;
|
||||
// char[] checksum = new char[4];
|
||||
//
|
||||
// for (i = 2; i < (msg.length - 8) / 4; i++) {
|
||||
// for (j = 0; j < 4; j++) {
|
||||
// checksum[j] ^= msg[i * 4 + j];
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// for (i = 0; i < 4; i++) {
|
||||
// int k = ~checksum[i] & 0xff;
|
||||
// checksum[i] = (char) k;
|
||||
// }
|
||||
//
|
||||
// StringBuffer sb = new StringBuffer();
|
||||
// for (i = 0; i < 4; i++) {
|
||||
// String s = Integer.toHexString(checksum[i] & 0xff).toUpperCase();
|
||||
// if (s.length() < 2) {
|
||||
// sb.append("0").append(s);
|
||||
// }
|
||||
// else {
|
||||
// sb.append(s);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// return sb.toString().toCharArray();
|
||||
// }
|
||||
|
||||
/**
|
||||
* 为比对字节好用,显示输出格尺
|
||||
*/
|
||||
public static void showGrid() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
System.out.print("0123456789");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param buf
|
||||
* byte[]
|
||||
*/
|
||||
public static void showBytes(byte[] buf) {
|
||||
if (buf == null) {
|
||||
buf = new byte[0];
|
||||
}
|
||||
String hex = "";
|
||||
byte[] s = new byte[16];
|
||||
System.out.println("[BYTES INFO] : LENGTH = " + buf.length + "(0x"
|
||||
+ Integer.toHexString(buf.length) + ")");
|
||||
for (int i = 0; i < buf.length; i++) {
|
||||
if (i % 16 == 0) { // 行号
|
||||
hex = Integer.toHexString((i & 0xff) / 16); // hex 字符
|
||||
if (hex.length() == 1) {
|
||||
hex = "0" + hex;
|
||||
}
|
||||
System.out.print("[" + hex + "] ");
|
||||
}
|
||||
|
||||
hex = Integer.toHexString(((byte) buf[i]) & 0xff); // hex 字符
|
||||
if (hex.length() == 1) {
|
||||
hex = "0" + hex;
|
||||
}
|
||||
System.out.print(hex + " "); // 输出HEX
|
||||
s[i % 16] = buf[i];
|
||||
|
||||
if (i != 0 && i % 8 == 7 && i % 16 != 15) { // 8 字节
|
||||
System.out.print(" ");
|
||||
}
|
||||
|
||||
if (i != 0 && (i % 16 == 15 || i == buf.length - 1)) { // 16字节或结束
|
||||
if (i % 16 != 15) { // 补空格
|
||||
for (int k = i % 16; k < 16; k++) {
|
||||
if (k == 7) {
|
||||
System.out.print(" ");
|
||||
} else {
|
||||
System.out.print(" ");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
System.out.print(" "); // 输出可打印字符
|
||||
byte c = 126;
|
||||
for (int j = 0; j < i % 16 + 1; j++) {
|
||||
if (s[j] == 0 || s[j] <= ' ' || s[j] > c) {
|
||||
s[j] = '.';
|
||||
}
|
||||
System.out.print((char) s[j]);
|
||||
}
|
||||
|
||||
System.out.print("\n"); // 输出换行
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param args
|
||||
* String[]
|
||||
*/
|
||||
// @SuppressWarnings("unused")
|
||||
// public static void main(String[] args) {
|
||||
// // /byte[] hex = hex2bytes("013233");
|
||||
// // /String hhh = bytes2hex(hex);
|
||||
//
|
||||
// String dd =
|
||||
// "SCSC003C1.00JS123456UASUAS 00000000DLGCON 00000001TXBEG HBHB";
|
||||
// // C5F6F7B2
|
||||
// // /char[] s = dd.toCharArray();
|
||||
// showBytes(dd.getBytes());
|
||||
// //
|
||||
// System.out.println(ByteUtils.getZteIHLRChecksum("HBHB".toCharArray()));
|
||||
// // // it
|
||||
// // is ok. B7BDB7BD
|
||||
// // System.out.println(ByteUtils.getZteIHLRChecksum(s)); // it is ok.
|
||||
// // System.out.println(ByteUtils.getZtePCSChecksum(s));
|
||||
//
|
||||
// byte[] length = new byte[20];
|
||||
// byte[] to = new byte[10];
|
||||
// ByteUtils.memset(length, (byte) '0', 0, 20);
|
||||
// ByteUtils.memcpy(to, 0, length, 20);
|
||||
// System.out.println(new String(ByteUtils.toHexBytes(255, 2, (byte) '0')));
|
||||
// System.out.println(new String(ByteUtils.fillHead(to, 20, (byte) '1')));
|
||||
// System.out.println(new String(ByteUtils.fillTail(to, 15, (byte) '9')));
|
||||
// System.out.println(new String(ByteUtils.copyto(to, "hello!".getBytes(),
|
||||
// 0, 10)));
|
||||
// System.out.println(new String(ByteUtils.copyto(to,
|
||||
// "Hello world!".getBytes(), 2, 15)));
|
||||
//
|
||||
// System.out.println(new String(ByteUtils.copy(to, 5, 6)));
|
||||
// System.out.println(new String(ByteUtils.delete("Hello world".getBytes(),
|
||||
// 5, 6)));
|
||||
// System.out.println(new String(ByteUtils.insert(to, "Gogogo!".getBytes(),
|
||||
// 5, 5)));
|
||||
// ByteUtils.memset(length, (byte) '5', 10, 10);
|
||||
// System.out.println(new String(length));
|
||||
// System.out.println(new String(ByteUtils.insert(length,
|
||||
// "Gogogo!".getBytes(), 8, 8)));
|
||||
//
|
||||
// ByteUtils.showGrid();
|
||||
//
|
||||
// System.out.println(new String(int2bytes(0x1c1d1e1f)));
|
||||
//
|
||||
// int n = htonl(0x12345678);
|
||||
// System.out.println(Integer.toHexString(n));
|
||||
// n = ntohl(n);
|
||||
// System.out.println(Integer.toHexString(n));
|
||||
//
|
||||
// n = htons(0x1234);
|
||||
// System.out.println(Integer.toHexString(n));
|
||||
// n = htons(n);
|
||||
// System.out.println(Integer.toHexString(n));
|
||||
//
|
||||
// byte[] z = htonlbytes(0x12345678);
|
||||
// System.out.println(new String(z));
|
||||
// z = htonsbytes(0x1234);
|
||||
// System.out.println(new String(z));
|
||||
//
|
||||
// byte[] j = ByteUtils.short2bytes(0x94d8);
|
||||
// System.out.println(Integer.toHexString(0x94d8));
|
||||
//
|
||||
// int ddd = ByteUtils.byte2short(j);
|
||||
// }
|
||||
}
|
||||
631
comm/Kernel/src/kernel/util/ClassTools.java
Executable file
631
comm/Kernel/src/kernel/util/ClassTools.java
Executable file
@@ -0,0 +1,631 @@
|
||||
package kernel.util;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import lombok.experimental.UtilityClass;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.core.BridgeMethodResolver;
|
||||
import org.springframework.core.DefaultParameterNameDiscoverer;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.core.ParameterNameDiscoverer;
|
||||
import org.springframework.core.annotation.AnnotatedElementUtils;
|
||||
import org.springframework.core.annotation.SynthesizingMethodParameter;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.net.URL;
|
||||
import java.net.URLDecoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
|
||||
/**
|
||||
* 类工具类
|
||||
*
|
||||
* @author L.cm
|
||||
*/
|
||||
@UtilityClass
|
||||
public class ClassTools extends org.springframework.util.ClassUtils {
|
||||
private final static Logger logger = LogManager.getLogger(ClassTools.class);
|
||||
|
||||
// 缓存起来,提升效率,field:完整类名#属性名
|
||||
private final static ConcurrentHashMap<String, Field> cacheMap = new ConcurrentHashMap();
|
||||
|
||||
private final ParameterNameDiscoverer PARAMETERNAMEDISCOVERER = new DefaultParameterNameDiscoverer();
|
||||
|
||||
/**
|
||||
* 获取方法参数信息
|
||||
* @param constructor 构造器
|
||||
* @param parameterIndex 参数序号
|
||||
* @return {MethodParameter}
|
||||
*/
|
||||
public MethodParameter getMethodParameter(Constructor<?> constructor, int parameterIndex) {
|
||||
MethodParameter methodParameter = new SynthesizingMethodParameter(constructor, parameterIndex);
|
||||
methodParameter.initParameterNameDiscovery(PARAMETERNAMEDISCOVERER);
|
||||
return methodParameter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取方法参数信息
|
||||
* @param method 方法
|
||||
* @param parameterIndex 参数序号
|
||||
* @return {MethodParameter}
|
||||
*/
|
||||
public MethodParameter getMethodParameter(Method method, int parameterIndex) {
|
||||
MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex);
|
||||
methodParameter.initParameterNameDiscovery(PARAMETERNAMEDISCOVERER);
|
||||
return methodParameter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Annotation
|
||||
* @param method Method
|
||||
* @param annotationType 注解类
|
||||
* @param <A> 泛型标记
|
||||
* @return {Annotation}
|
||||
*/
|
||||
public <A extends Annotation> A getAnnotation(Method method, Class<A> annotationType) {
|
||||
Class<?> targetClass = method.getDeclaringClass();
|
||||
// The method may be on an interface, but we need attributes from the target
|
||||
// class.
|
||||
// If the target class is null, the method will be unchanged.
|
||||
Method specificMethod = getMostSpecificMethod(method, targetClass);
|
||||
// If we are dealing with method with generic parameters, find the original
|
||||
// method.
|
||||
specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
|
||||
// 先找方法,再找方法上的类
|
||||
A annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod, annotationType);
|
||||
|
||||
if (null != annotation) {
|
||||
return annotation;
|
||||
}
|
||||
// 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
|
||||
return AnnotatedElementUtils.findMergedAnnotation(specificMethod.getDeclaringClass(), annotationType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Annotation
|
||||
* @param handlerMethod HandlerMethod
|
||||
* @param annotationType 注解类
|
||||
* @param <A> 泛型标记
|
||||
* @return {Annotation}
|
||||
*/
|
||||
public <A extends Annotation> A getAnnotation(HandlerMethod handlerMethod, Class<A> annotationType) {
|
||||
// 先找方法,再找方法上的类
|
||||
A annotation = handlerMethod.getMethodAnnotation(annotationType);
|
||||
if (null != annotation) {
|
||||
return annotation;
|
||||
}
|
||||
// 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
|
||||
Class<?> beanType = handlerMethod.getBeanType();
|
||||
return AnnotatedElementUtils.findMergedAnnotation(beanType, annotationType);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description: 判断是否是基础类型
|
||||
* 注意:将枚举类型也当成了基础类型
|
||||
* @time 2023年1月29日 下午3:05:19
|
||||
* @author caster2023
|
||||
* @param clazz
|
||||
* @return
|
||||
* boolean
|
||||
* @throws
|
||||
*/
|
||||
public static boolean isBaseType(Class<?> clazz) {
|
||||
if (clazz.isPrimitive()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (clazz == Integer.class) {
|
||||
return true;
|
||||
} else if (clazz == Float.class) {
|
||||
return true;
|
||||
} else if (clazz == Long.class) {
|
||||
return true;
|
||||
} else if (clazz == Double.class) {
|
||||
return true;
|
||||
} else if (clazz == Byte.class) {
|
||||
return true;
|
||||
} else if (clazz == Boolean.class) {
|
||||
return true;
|
||||
} else if (clazz == String.class) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static List<Field> listDateTypeFields(Class clazz) {
|
||||
List<Field> dateTypeFieldList = new ArrayList();
|
||||
List<Field> allFieldList = getAllFields(clazz);
|
||||
for (Field oneField : allFieldList) {
|
||||
Class fieldType = oneField.getType();
|
||||
if (fieldType == Date.class) {
|
||||
dateTypeFieldList.add(oneField);
|
||||
}
|
||||
}
|
||||
|
||||
return dateTypeFieldList;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static List<Class> getAllClassByInterface(Class c) {
|
||||
List returnClassList = new ArrayList<Class>();
|
||||
// 判断是不是接口,不是接口不作处理
|
||||
if (c.isInterface()) {
|
||||
Package pkg = c.getPackage();
|
||||
String packageName = "";
|
||||
if (pkg != null) {
|
||||
packageName = c.getPackage().getName(); // 获得当前包名
|
||||
} else {
|
||||
packageName = c.getName().substring(0, c.getName().lastIndexOf(".")); // 获得当前包名
|
||||
}
|
||||
try {
|
||||
List<Class> allClass = getClasses(packageName, c.getClassLoader());// 获得当前包以及子包下的所有类
|
||||
|
||||
// 判断是否是一个接口
|
||||
for (int i = 0; i < allClass.size(); i++) {
|
||||
if (c.isAssignableFrom(allClass.get(i))) {
|
||||
if (!c.equals(allClass.get(i))) {
|
||||
returnClassList.add(allClass.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
RuntimeException ex = new RuntimeException(
|
||||
"[ClassUtil getAllClassByInterface] getAllClassByInterface failed.");
|
||||
ex.initCause(e);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
return returnClassList;
|
||||
}
|
||||
|
||||
public static List<Class> getClasses(String packageName, ClassLoader classLoader)
|
||||
throws ClassNotFoundException, IOException {
|
||||
String path = packageName.replace(".", "/");
|
||||
Enumeration<URL> resources = classLoader.getResources(path);
|
||||
List<File> dirs = new ArrayList<File>();
|
||||
while (resources.hasMoreElements()) {
|
||||
URL resource = resources.nextElement();
|
||||
dirs.add(new File(resource.getFile()));
|
||||
}
|
||||
|
||||
ArrayList<Class> classes = new ArrayList<Class>();
|
||||
for (File directory : dirs) {
|
||||
classes.addAll(findClass(directory, packageName, classLoader));
|
||||
}
|
||||
|
||||
return classes;
|
||||
}
|
||||
|
||||
private static List<Class> findClass(File directory, String packageName, ClassLoader classLoader)
|
||||
throws ClassNotFoundException {
|
||||
List<Class> classes = new ArrayList<Class>();
|
||||
if (!directory.exists()) {
|
||||
return classes;
|
||||
}
|
||||
File[] files = directory.listFiles();
|
||||
for (File file : files) {
|
||||
if (file.isDirectory()) {
|
||||
assert !file.getName().contains(".");
|
||||
classes.addAll(findClass(file, packageName + "." + file.getName(), classLoader));
|
||||
} else if (file.getName().endsWith(".class")) {
|
||||
classes.add(Class.forName(packageName + "." + file.getName().substring(0, file.getName().length() - 6),
|
||||
false, classLoader));
|
||||
}
|
||||
}
|
||||
return classes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断类是否函数类.<br>
|
||||
* 首先,类不能是抽象的,其次,类必须实现函数接口
|
||||
*
|
||||
* @param c
|
||||
* 类
|
||||
* @return 是否是函数类
|
||||
*/
|
||||
public static boolean isFunction(Class<?> c, Class<?> interfaceClazz) {
|
||||
if (c == null) {
|
||||
return false;
|
||||
}
|
||||
if (c.isInterface()) {
|
||||
return false;
|
||||
}
|
||||
if (Modifier.isAbstract(c.getModifiers())) {
|
||||
return false;// 抽象
|
||||
}
|
||||
// Class<?>[] interfaces = c.getInterfaces();
|
||||
// if (interfaces == null || interfaces.length == 0) {
|
||||
// return false;
|
||||
// }
|
||||
// for (Class<?> i : interfaces) {
|
||||
// if (i == IFunction.class) {
|
||||
// return true;
|
||||
// }
|
||||
// }
|
||||
return interfaceClazz.isAssignableFrom(c);
|
||||
}
|
||||
|
||||
public static boolean isAnnotation(Class<? extends Annotation> ann, Class<?> c) {
|
||||
if (ann == null) {
|
||||
return false;
|
||||
}
|
||||
if (!c.isInterface()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return c.isAnnotationPresent(ann);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取项目的path下所有的文件夹和文件
|
||||
*
|
||||
* @return 文件列表
|
||||
*/
|
||||
private static List<File> listPaths() {
|
||||
List<File> files = new ArrayList<File>();
|
||||
String jars = System.getProperty("java.class.path");
|
||||
if (jars == null) {
|
||||
logger.warn("[ClassUtil listPaths] java.class.path is null!");
|
||||
return files;
|
||||
} else {
|
||||
// web 容器下的类路径可能不同,查找 WEB-INF下的类文件
|
||||
logger.info("java.class.path:" + jars);
|
||||
}
|
||||
|
||||
URL root = Thread.currentThread().getContextClassLoader().getResource("");// ClassUtil.class.getClassLoader().getResource("");
|
||||
if (root == null) {
|
||||
logger.error("path root is null!");
|
||||
return files;
|
||||
}
|
||||
String path = null;
|
||||
try {
|
||||
path = URLDecoder.decode(root.getFile(), "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
logger.error("[ClassUtil listPaths] decode the root file error:", e);
|
||||
return files;
|
||||
}
|
||||
|
||||
File dir = new File(path);
|
||||
String[] array = (jars).split(";");
|
||||
if (array != null) {
|
||||
for (String s : array) {
|
||||
if (s == null) {
|
||||
continue;
|
||||
}
|
||||
File f = new File(s);
|
||||
if (f.exists()) {
|
||||
files.add(f);
|
||||
} else {
|
||||
// 有些jar就在系统目录下,省略了路径,要加上
|
||||
File jar = new File(dir, s);
|
||||
if (jar.exists()) {
|
||||
files.add(jar);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据接口类,查找所有实现了指定接口的类
|
||||
*
|
||||
* @param pkg
|
||||
* 包名,此处只是为了限定,防止漫无目的的查找.不用设置也可以,就要每找到一个类就要加载一次判断了
|
||||
* @return 类列表
|
||||
*/
|
||||
public static List<Class<?>> getClassesByInterface(String pkg, Class<?> interfaceClazz) {
|
||||
List<Class<?>> list = new ArrayList<Class<?>>();
|
||||
for (File f : listPaths()) {
|
||||
// 如果是以文件的形式保存在服务器上
|
||||
if (f.isDirectory()) {
|
||||
// 获取包的物理路径
|
||||
String path = pkg.replace('.', File.separatorChar);
|
||||
dirWalker(interfaceClazz, path, f, list);
|
||||
} else {// 尝试是否是jar文件
|
||||
// 获取jar
|
||||
JarFile jar = null;
|
||||
try {
|
||||
jar = new JarFile(f);
|
||||
} catch (IOException e) {
|
||||
// 有可能不是一个jar
|
||||
}
|
||||
if (jar == null) {
|
||||
continue;
|
||||
}
|
||||
String path = pkg.replace('.', '/');
|
||||
// 从此jar包 得到一个枚举类
|
||||
Enumeration<JarEntry> entries = jar.entries();
|
||||
// 同样的进行循环迭代
|
||||
while (entries.hasMoreElements()) {
|
||||
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
|
||||
JarEntry entry = entries.nextElement();
|
||||
String name = entry.getName();
|
||||
// 如果是以/开头的
|
||||
if (name.charAt(0) == '/') {
|
||||
// 获取后面的字符串
|
||||
name = name.substring(1);
|
||||
}
|
||||
// 如果前半部分和定义的包名相同
|
||||
if (name.contains(path)) {
|
||||
if (name.endsWith(".class") && !entry.isDirectory()) {
|
||||
name = name.replace("/", ".").substring(0, name.lastIndexOf("."));
|
||||
try {
|
||||
Class<?> c = Class.forName(name);
|
||||
if (isFunction(c, interfaceClazz)) {
|
||||
list.add(c);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 找不到无所谓了
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 根据接口类,查找所有实现了指定接口的类
|
||||
*
|
||||
* @param pkg
|
||||
* 包名,此处只是为了限定,防止漫无目的的查找.不用设置也可以,就要每找到一个类就要加载一次判断了
|
||||
* @return 类列表
|
||||
*/
|
||||
public static List<Class<?>> getClassesByAnnotation(String pkg, Class<? extends Annotation> ann) {
|
||||
List<Class<?>> list = new ArrayList<Class<?>>();
|
||||
for (File f : listPaths()) {
|
||||
// 如果是以文件的形式保存在服务器上
|
||||
if (f.isDirectory()) {
|
||||
// 获取包的物理路径
|
||||
String path = pkg.replace('.', File.separatorChar);
|
||||
dirWalker2(ann, path, pkg, f, list);
|
||||
} else {// 尝试是否是jar文件
|
||||
// 获取jar
|
||||
JarFile jar = null;
|
||||
try {
|
||||
jar = new JarFile(f);
|
||||
} catch (IOException e) {
|
||||
// 有可能不是一个jar
|
||||
}
|
||||
if (jar == null) {
|
||||
continue;
|
||||
}
|
||||
String path = pkg.replace('.', '/');
|
||||
// 从此jar包 得到一个枚举类
|
||||
Enumeration<JarEntry> entries = jar.entries();
|
||||
// 同样的进行循环迭代
|
||||
while (entries.hasMoreElements()) {
|
||||
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
|
||||
JarEntry entry = entries.nextElement();
|
||||
String name = entry.getName();
|
||||
// 如果是以/开头的
|
||||
if (name.charAt(0) == '/') {
|
||||
// 获取后面的字符串
|
||||
name = name.substring(1);
|
||||
}
|
||||
// 如果前半部分和定义的包名相同
|
||||
if (name.contains(path)) {
|
||||
if (name.endsWith(".class") && !entry.isDirectory()) {
|
||||
name = name.replace("/", ".").substring(0, name.lastIndexOf("."));
|
||||
try {
|
||||
Class<?> c = Class.forName(name);
|
||||
if (isAnnotation(ann, c)) {
|
||||
list.add(c);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 找不到无所谓了
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 遍历文件夹下所有的类
|
||||
*
|
||||
* @param path
|
||||
* 包路径
|
||||
* @param file
|
||||
* 文件
|
||||
* @param list
|
||||
* 保存类列表
|
||||
*/
|
||||
private static void dirWalker(Class<?> interfaceClazz, String path, File file, List<Class<?>> list) {
|
||||
if (file.exists()) {
|
||||
if (file.isDirectory()) {
|
||||
for (File f : file.listFiles()) {
|
||||
dirWalker(interfaceClazz, path, f, list);
|
||||
}
|
||||
} else {
|
||||
Class<?> c = loadClassByFile(interfaceClazz, path, file);
|
||||
if (c != null) {
|
||||
list.add(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void dirWalker2(Class<? extends Annotation> ann, String path, String pkg, File file, List<Class<?>> list) {
|
||||
if (file.exists()) {
|
||||
if (file.isDirectory()) {
|
||||
for (File f : file.listFiles()) {
|
||||
dirWalker2(ann, path, pkg, f, list);
|
||||
}
|
||||
} else {
|
||||
Class<?> c = loadClassWithAnnotation(ann, path, pkg, file);
|
||||
if (c != null) {
|
||||
list.add(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件加载类
|
||||
*
|
||||
* @param pkg
|
||||
* 包路径
|
||||
* @param file
|
||||
* 文件
|
||||
* @return 类或者null
|
||||
*/
|
||||
private static Class<?> loadClassByFile(Class<?> interfaceClazz, String pkg, File file) {
|
||||
if (!file.isFile()) {
|
||||
return null;
|
||||
}
|
||||
String name = file.getName();
|
||||
if (name.endsWith(".class")) {
|
||||
String ap = file.getAbsolutePath();
|
||||
if (!ap.contains(pkg)) {
|
||||
return null;
|
||||
}
|
||||
name = ap.substring(ap.indexOf(pkg) + pkg.length());
|
||||
if (name.startsWith(File.separator)) {
|
||||
name = name.substring(1);
|
||||
}
|
||||
String path = (pkg + "." + name.substring(0, name.lastIndexOf("."))).replace(File.separatorChar, '.');
|
||||
try {
|
||||
Class<?> c = Class.forName(path);
|
||||
if (isFunction(c, interfaceClazz)) {
|
||||
return c;
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Class<?> loadClassWithAnnotation(Class<? extends Annotation> ann, String path2, String pkg, File file) {
|
||||
if (!file.isFile()) {
|
||||
return null;
|
||||
}
|
||||
String name = file.getName();
|
||||
if (name.endsWith(".class")) {
|
||||
String ap = file.getAbsolutePath();
|
||||
ap = ap.replace(File.separator, ".");
|
||||
if (!ap.contains(pkg)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
name = ap.substring(ap.indexOf(pkg) + pkg.length());
|
||||
if (name.startsWith(File.separator)) {
|
||||
name = name.substring(1);
|
||||
}
|
||||
String path = (pkg + "." + name.substring(0, name.lastIndexOf("."))).replace(File.separatorChar, '.');
|
||||
try {
|
||||
Class<?> c = Class.forName(path);
|
||||
if (isAnnotation(ann, c)) {
|
||||
return c;
|
||||
}
|
||||
} catch (ClassNotFoundException e) {
|
||||
// do nothing
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Description: 获得某个类的所有声明的字段,即包括public、private和proteced
|
||||
* @time 2023年1月29日 下午3:38:15
|
||||
* @author caster2023
|
||||
* @param clazz
|
||||
* @return
|
||||
* List<Field>
|
||||
* @throws
|
||||
*/
|
||||
public static List<Field> getAllFields(Class<?> clazz) {
|
||||
List<Field> fieldList = new ArrayList();
|
||||
for(; clazz != Object.class ; clazz = clazz.getSuperclass()) {
|
||||
try {
|
||||
Field[] localFields = clazz.getDeclaredFields();
|
||||
for (Field oneField : localFields) {
|
||||
fieldList.add(oneField);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return fieldList;
|
||||
}
|
||||
|
||||
public static Field getFieldByName(Class<?> clazz, String propertyName) {
|
||||
if (clazz == null || StrUtil.isBlank(propertyName)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String key = clazz.getName() + "#" + propertyName;
|
||||
Field retField = cacheMap.get(key);
|
||||
if (retField != null) {
|
||||
return retField;
|
||||
}
|
||||
|
||||
List<Field> optionFields = new ArrayList();
|
||||
|
||||
List<Field> allFieldList = getAllFields(clazz);
|
||||
for(Field oneField : allFieldList) {
|
||||
if (oneField.getName().equals(propertyName)) {
|
||||
retField = oneField;
|
||||
optionFields.add(oneField);
|
||||
break;
|
||||
} else if (oneField.getName().equalsIgnoreCase(propertyName)) {
|
||||
optionFields.add(oneField);
|
||||
}
|
||||
}
|
||||
if (retField == null) {
|
||||
for(Field oneField : allFieldList) {
|
||||
if (oneField.getType() == boolean.class) {
|
||||
String tmpName = "is" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
|
||||
if (oneField.getName().equals(tmpName)) {
|
||||
retField = oneField;
|
||||
optionFields.add(oneField);
|
||||
break;
|
||||
} else if (oneField.getName().equalsIgnoreCase(tmpName)) {
|
||||
optionFields.add(oneField);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (retField != null) {
|
||||
cacheMap.putIfAbsent(key, retField);
|
||||
return retField;
|
||||
}
|
||||
if (optionFields.size() > 0) {
|
||||
logger.warn("未能在类:{} 中找到严格匹配属性名:{} 的字段对象,将返回一个疑似字段:{}", clazz, propertyName, optionFields.get(0).getName());
|
||||
cacheMap.putIfAbsent(key, optionFields.get(0));
|
||||
return optionFields.get(0);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
230
comm/Kernel/src/kernel/util/ConvertUtil.java
Executable file
230
comm/Kernel/src/kernel/util/ConvertUtil.java
Executable file
@@ -0,0 +1,230 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
public class ConvertUtil {
|
||||
public final static char[] BToA = "0123456789abcdef".toCharArray();
|
||||
|
||||
private ConvertUtil() {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 把16进制字符串转换成字节数组
|
||||
*
|
||||
* @param hex
|
||||
* @return
|
||||
*/
|
||||
public static byte[] hexStringToByte(String hex) {
|
||||
int len = (hex.length() / 2);
|
||||
byte[] result = new byte[len];
|
||||
char[] achar = hex.toCharArray();
|
||||
for (int i = 0; i < len; i++) {
|
||||
int pos = i * 2;
|
||||
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static byte toByte(char c) {
|
||||
byte b = (byte) "0123456789ABCDEF".indexOf(c);
|
||||
return b;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把字节数组转换成16进制字符串
|
||||
*
|
||||
* @param bArray
|
||||
* @return
|
||||
*/
|
||||
public static final String bytesToHexString(byte[] bArray) {
|
||||
if (bArray == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuffer sb = new StringBuffer(bArray.length);
|
||||
String sTemp;
|
||||
for (int i = 0; i < bArray.length; i++) {
|
||||
sTemp = Integer.toHexString(0xFF & bArray[i]);
|
||||
if (sTemp.length() < 2)
|
||||
sb.append(0);
|
||||
sb.append(sTemp.toUpperCase());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 把字节数组转换为对象
|
||||
*
|
||||
* @param bytes
|
||||
* @return
|
||||
* @throws IOException
|
||||
* @throws ClassNotFoundException
|
||||
*/
|
||||
public static final Object bytesToObject(byte[] bytes) throws IOException, ClassNotFoundException {
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
|
||||
ObjectInputStream oi = new ObjectInputStream(in);
|
||||
Object o = oi.readObject();
|
||||
oi.close();
|
||||
return o;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把可序列化对象转换成字节数组
|
||||
*
|
||||
* @param s
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static final byte[] objectToBytes(Serializable s) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
ObjectOutputStream ot = new ObjectOutputStream(out);
|
||||
ot.writeObject(s);
|
||||
ot.flush();
|
||||
ot.close();
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
public static final String objectToHexString(Serializable s) throws IOException {
|
||||
return bytesToHexString(objectToBytes(s));
|
||||
}
|
||||
|
||||
public static final Object hexStringToObject(String hex) throws IOException, ClassNotFoundException {
|
||||
return bytesToObject(hexStringToByte(hex));
|
||||
}
|
||||
|
||||
/**
|
||||
* @函数功能: BCD码转为10进制串(阿拉伯数据)
|
||||
* @输入参数: BCD码
|
||||
* @输出结果: 10进制串
|
||||
*/
|
||||
public static String bcd2Str(byte[] bytes) {
|
||||
StringBuffer temp = new StringBuffer(bytes.length * 2);
|
||||
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
temp.append((byte) ((bytes[i] & 0xf0) >>> 4));
|
||||
temp.append((byte) (bytes[i] & 0x0f));
|
||||
}
|
||||
return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp.toString().substring(1) : temp.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* @函数功能: 10进制串转为BCD码
|
||||
* @输入参数: 10进制串
|
||||
* @输出结果: BCD码
|
||||
*/
|
||||
public static byte[] str2Bcd(String asc) {
|
||||
int len = asc.length();
|
||||
int mod = len % 2;
|
||||
|
||||
if (mod != 0) {
|
||||
asc = "0" + asc;
|
||||
len = asc.length();
|
||||
}
|
||||
|
||||
byte abt[] = new byte[len];
|
||||
if (len >= 2) {
|
||||
len = len / 2;
|
||||
}
|
||||
|
||||
byte bbt[] = new byte[len];
|
||||
abt = asc.getBytes();
|
||||
int j, k;
|
||||
|
||||
for (int p = 0; p < asc.length() / 2; p++) {
|
||||
if ((abt[2 * p] >= '0') && (abt[2 * p] <= '9')) {
|
||||
j = abt[2 * p] - '0';
|
||||
} else if ((abt[2 * p] >= 'a') && (abt[2 * p] <= 'z')) {
|
||||
j = abt[2 * p] - 'a' + 0x0a;
|
||||
} else {
|
||||
j = abt[2 * p] - 'A' + 0x0a;
|
||||
}
|
||||
|
||||
if ((abt[2 * p + 1] >= '0') && (abt[2 * p + 1] <= '9')) {
|
||||
k = abt[2 * p + 1] - '0';
|
||||
} else if ((abt[2 * p + 1] >= 'a') && (abt[2 * p + 1] <= 'z')) {
|
||||
k = abt[2 * p + 1] - 'a' + 0x0a;
|
||||
} else {
|
||||
k = abt[2 * p + 1] - 'A' + 0x0a;
|
||||
}
|
||||
|
||||
int a = (j << 4) + k;
|
||||
byte b = (byte) a;
|
||||
bbt[p] = b;
|
||||
}
|
||||
return bbt;
|
||||
}
|
||||
|
||||
public static String BCD2ASC(byte[] bytes) {
|
||||
StringBuffer temp = new StringBuffer(bytes.length * 2);
|
||||
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
int h = ((bytes[i] & 0xf0) >>> 4);
|
||||
int l = (bytes[i] & 0x0f);
|
||||
temp.append(BToA[h]).append(BToA[l]);
|
||||
}
|
||||
return temp.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 两字符数组异或
|
||||
*/
|
||||
public static byte[] byteArrXor(byte[] arr1, byte[] arr2, int len) {
|
||||
byte[] dest = new byte[len];
|
||||
|
||||
if ((arr1.length < len) || (arr2.length < len)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (int i = 0; i < len; i++) {
|
||||
dest[i] = (byte) (arr1[i] ^ arr2[i]);
|
||||
}
|
||||
|
||||
return dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* MD5加密字符串,返回加密后的16进制字符串
|
||||
*
|
||||
* @param origin
|
||||
* @return
|
||||
*/
|
||||
public static String MD5EncodeToHex(String origin) {
|
||||
return bytesToHexString(MD5Encode(origin));
|
||||
}
|
||||
|
||||
/**
|
||||
* MD5加密字符串,返回加密后的字节数组
|
||||
*
|
||||
* @param origin
|
||||
* @return
|
||||
*/
|
||||
public static byte[] MD5Encode(String origin) {
|
||||
return MD5Encode(origin.getBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* MD5加密字节数组,返回加密后的字节数组
|
||||
*
|
||||
* @param bytes
|
||||
* @return
|
||||
*/
|
||||
public static byte[] MD5Encode(byte[] bytes) {
|
||||
MessageDigest md = null;
|
||||
try {
|
||||
md = MessageDigest.getInstance("MD5");
|
||||
return md.digest(bytes);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return new byte[0];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
1002
comm/Kernel/src/kernel/util/DateTimeTools.java
Executable file
1002
comm/Kernel/src/kernel/util/DateTimeTools.java
Executable file
File diff suppressed because it is too large
Load Diff
710
comm/Kernel/src/kernel/util/DateUtils.java
Executable file
710
comm/Kernel/src/kernel/util/DateUtils.java
Executable file
@@ -0,0 +1,710 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.apache.commons.lang.time.DateFormatUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public abstract class DateUtils {
|
||||
|
||||
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
|
||||
|
||||
public static final String DEFAULT_TIME_ZONE = "GMT+8";
|
||||
|
||||
public static final String NORMAL_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
public static final String UTC_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
|
||||
|
||||
public static Date toDate(String string) {
|
||||
return toDate(string, DEFAULT_DATE_FORMAT);
|
||||
}
|
||||
|
||||
public static Date toDate(String string, String pattern) {
|
||||
return toDate(string, pattern, TimeZone.getTimeZone(DEFAULT_TIME_ZONE));
|
||||
}
|
||||
|
||||
public static Date toDate(String string, String pattern, TimeZone timeZone) {
|
||||
try {
|
||||
SimpleDateFormat sdf = (SimpleDateFormat) createDateFormat(pattern, timeZone);
|
||||
return sdf.parse(string);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static String format(Date date, String pattern, TimeZone timeZone) {
|
||||
DateFormat df = createDateFormat(pattern, timeZone);
|
||||
return df.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* Description: 根据指定的pattern格式化date
|
||||
|
||||
*/
|
||||
public static String format(Date date, String pattern) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
}
|
||||
DateFormat df = createDateFormat(pattern);
|
||||
return df.format(date);
|
||||
}
|
||||
|
||||
public static DateFormat createDateFormat(String pattern) {
|
||||
return createDateFormat(pattern, TimeZone.getTimeZone(DEFAULT_TIME_ZONE));
|
||||
}
|
||||
|
||||
public static DateFormat createDateFormat(String pattern, TimeZone timeZone) {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
|
||||
TimeZone gmt = timeZone;
|
||||
sdf.setTimeZone(gmt);
|
||||
sdf.setLenient(true);
|
||||
return sdf;
|
||||
}
|
||||
|
||||
public static int getYear(java.util.Date date) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(date);
|
||||
return calendar.get(Calendar.YEAR);
|
||||
}
|
||||
|
||||
public static String getShortYear(java.util.Date date) {
|
||||
String year = getYear(date) + "";
|
||||
int length = year.length();
|
||||
return year.substring(length - 2, length);
|
||||
}
|
||||
|
||||
public static int getMonth(java.util.Date date) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(date);
|
||||
return calendar.get(Calendar.MONTH) + 1;
|
||||
}
|
||||
|
||||
public static int getDay(java.util.Date date) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(date);
|
||||
return calendar.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
|
||||
public static int getHour(java.util.Date date) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(date);
|
||||
return calendar.get(Calendar.HOUR_OF_DAY);
|
||||
}
|
||||
|
||||
public static int getMinute(java.util.Date date) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(date);
|
||||
return calendar.get(Calendar.MINUTE);
|
||||
}
|
||||
|
||||
public static int getSecond(java.util.Date date) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(date);
|
||||
return calendar.get(Calendar.SECOND);
|
||||
}
|
||||
|
||||
public static Date addMilliSecond(java.util.Date oldDate, int addMilliSecond) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.MILLISECOND, addMilliSecond);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date addSecond(java.util.Date oldDate, int addSecond) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.SECOND, addSecond);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date addMinute(java.util.Date oldDate, int addMinutes) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.MINUTE, addMinutes);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date addHour(java.util.Date oldDate, int addHours) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.HOUR, addHours);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date addDay(java.util.Date oldDate, int addDays) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.DATE, addDays);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date addMonth(java.util.Date oldDate, int addMonths) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.MONTH, addMonths);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date addYear(java.util.Date oldDate, int addYears) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.YEAR, addYears);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static long calcTimeBetween(String unitType, Date startDate, Date endDate) {
|
||||
Assert.hasText(unitType);
|
||||
Assert.notNull(startDate);
|
||||
Assert.notNull(endDate);
|
||||
long between = endDate.getTime() - startDate.getTime();
|
||||
if (unitType.equals("ms")) {
|
||||
return between;
|
||||
} else if (unitType.equals("s")) {
|
||||
return between / 1000;// 返回秒
|
||||
} else if (unitType.equals("m")) {
|
||||
return between / 60000;// 返回分钟
|
||||
} else if (unitType.equals("h")) {
|
||||
return between / 3600000;// 返回小时
|
||||
} else if (unitType.equals("d")) {
|
||||
return between / 86400000;// 返回天数
|
||||
} else {
|
||||
throw new IllegalArgumentException("the unitType is unknown");
|
||||
}
|
||||
}
|
||||
|
||||
public static long calcTimeBetweenInMillis(Date startDate, Date endDate) {
|
||||
return calcTimeBetween("ms", startDate, endDate);
|
||||
}
|
||||
|
||||
public static long calcTimeBetweenInSecond(Date startDate, Date endDate) {
|
||||
return calcTimeBetween("s", startDate, endDate);
|
||||
}
|
||||
|
||||
public static long calcTimeBetweenInMinute(Date startDate, Date endDate) {
|
||||
return calcTimeBetween("m", startDate, endDate);
|
||||
}
|
||||
|
||||
public static long calcTimeBetweenInHour(Date startDate, Date endDate) {
|
||||
return calcTimeBetween("h", startDate, endDate);
|
||||
}
|
||||
|
||||
public static long calcTimeBetweenInDay(Date startDate, Date endDate) {
|
||||
return calcTimeBetween("d", startDate, endDate);
|
||||
}
|
||||
|
||||
public static Date roundYear(Date date) {
|
||||
return org.apache.commons.lang3.time.DateUtils.round(date, Calendar.YEAR);
|
||||
}
|
||||
|
||||
public static Date roundMonth(Date date) {
|
||||
return org.apache.commons.lang3.time.DateUtils.round(date, Calendar.MONTH);
|
||||
}
|
||||
|
||||
public static Date roundDay(Date date) {
|
||||
return org.apache.commons.lang3.time.DateUtils.round(date, Calendar.DATE);
|
||||
}
|
||||
|
||||
public static Date roundHour(Date date) {
|
||||
return org.apache.commons.lang3.time.DateUtils.round(date, Calendar.HOUR);
|
||||
}
|
||||
|
||||
public static Date roundMinute(Date date) {
|
||||
return org.apache.commons.lang3.time.DateUtils.round(date, Calendar.MINUTE);
|
||||
}
|
||||
|
||||
public static Date roundSecond(Date date) {
|
||||
return org.apache.commons.lang3.time.DateUtils.round(date, Calendar.SECOND);
|
||||
}
|
||||
|
||||
public static Date truncateYear(Date date) {
|
||||
return org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.YEAR);
|
||||
}
|
||||
|
||||
public static Date truncateMonth(Date date) {
|
||||
return org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.MONTH);
|
||||
}
|
||||
|
||||
public static Date truncateDay(Date date) {
|
||||
return org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.DATE);
|
||||
}
|
||||
|
||||
public static Date truncateHour(Date date) {
|
||||
return org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.HOUR);
|
||||
|
||||
}
|
||||
|
||||
public static Date truncateMinute(Date date) {
|
||||
return org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.MINUTE);
|
||||
}
|
||||
|
||||
public static Date truncateSecond(Date date) {
|
||||
return org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.SECOND);
|
||||
}
|
||||
|
||||
public static Date setHour(Date oldDate, int newHour) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.set(Calendar.HOUR, newHour);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date setMinute(Date oldDate, int newMinute) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.set(Calendar.MINUTE, newMinute);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date setSecond(Date oldDate, int newSecond) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.set(Calendar.SECOND, newSecond);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param dt Date
|
||||
* @return boolean
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public static boolean isRYear(Date dt) {
|
||||
return (isRYear(1900 + dt.getYear()));
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param y int
|
||||
* @return boolean
|
||||
*/
|
||||
public static boolean isRYear(int y) {
|
||||
return (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一个日期的时间字符串
|
||||
*
|
||||
* @param dt Date
|
||||
* @return String
|
||||
*/
|
||||
public static String getTimeStr(Date dt) {
|
||||
return new SimpleDateFormat("HH:mm:ss").format(dt);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一个日期值的日期字符串
|
||||
*
|
||||
* @param dt Date
|
||||
* @return String
|
||||
*/
|
||||
public static String getDateStr(Date dt) {
|
||||
return new SimpleDateFormat("yyyy-MM-dd").format(dt);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一个日期值的带时间日期字符串
|
||||
*
|
||||
* @param dt Date
|
||||
* @return String
|
||||
*/
|
||||
public static String getLongDate(Date dt) {
|
||||
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dt);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param dt Date
|
||||
* @return String
|
||||
*/
|
||||
public static String toString(Date dt) {
|
||||
return format(dt, "yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
public static String toMillString(Date dt) {
|
||||
return format(dt, "yyyy-MM-dd HH:mm:ss.SSS");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param date Date
|
||||
* @return Timestamp added by jiayc
|
||||
*/
|
||||
public static java.sql.Timestamp dateToTimeStamp(java.util.Date date) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
} else {
|
||||
return new java.sql.Timestamp(date.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
public static final String DFS_MMdd = "MMdd";
|
||||
|
||||
public static final String DFS_yyyyMMdd = "yyyyMMdd";
|
||||
|
||||
public static final String DFS_yyMMdd = "yyMMdd";
|
||||
|
||||
public static final String DF_MMdd = "MM-dd";
|
||||
|
||||
public static final String DF_HHmm = "HH:mm";
|
||||
|
||||
public static final String DF_MMddHH = "MM-dd HH";
|
||||
|
||||
public static final String DF_yyyyMM = "yyyy-MM";
|
||||
|
||||
public static final String DF_yyyyMMdd = "yyyy-MM-dd";
|
||||
|
||||
public static final String DF_yyyyMMddHH = "yyyy-MM-dd HH";
|
||||
|
||||
public static final String DF_yyyyMMddHHmm = "yyyy-MM-dd HH:mm";
|
||||
|
||||
public static final String DF_yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
public static final String DF_yyyyMMddHHmmssS = "yyyy-MM-dd HH:mm:ss.SSS";
|
||||
public static final String DF_MMddyyyy = "MM/dd/yyyy";
|
||||
|
||||
private static String[] availableDF = { DFS_MMdd, DFS_yyyyMMdd, DFS_yyMMdd, DF_MMdd, DF_MMddHH, DF_HHmm,
|
||||
DF_yyyyMMdd, DF_yyyyMM, DF_yyyyMMddHH, DF_yyyyMMddHHmm, DF_yyyyMMddHHmmss, DF_yyyyMMddHHmmssS,
|
||||
DF_MMddyyyy };
|
||||
|
||||
static Log logger = LogFactory.getLog(DateUtils.class.getName());
|
||||
|
||||
protected DateUtils() {
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><><EFBFBD><EFBFBD><EFBFBD>String<6E><67>Date<74><65>ת<EFBFBD><D7AA><EFBFBD><EFBFBD>Ŀǰ<C4BF><C7B0><EFBFBD><EFBFBD>ܹ涨<DCB9><E6B6A8>ʽ<EFBFBD><CABD>DF_xxxx<78><78>DFS_xxxx<78>ƶ<EFBFBD><C6B6>ĸ<EFBFBD>ʽ<EFBFBD><CABD>
|
||||
*
|
||||
* @param strDate ת<><D7AA>ǰ<EFBFBD><C7B0><EFBFBD><EFBFBD><EFBFBD>ڣ<EFBFBD><DAA3>ַ<EFBFBD><D6B7>ʾ
|
||||
* @return Date ת<><D7AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
* @throws ParseException
|
||||
*/
|
||||
public static Date strToDate(String strDate) throws ParseException {
|
||||
if (StringUtils.isEmptyString(strDate)) {
|
||||
return null;
|
||||
}
|
||||
int _L = strDate.trim().length();
|
||||
String format = "";
|
||||
switch (_L) {
|
||||
case 4:
|
||||
format = DFS_MMdd;
|
||||
break;
|
||||
case 5:
|
||||
if (strDate.indexOf("-") != -1) {
|
||||
format = DF_MMdd;
|
||||
} else if (strDate.indexOf(":") != -1) {
|
||||
format = DF_HHmm;
|
||||
}
|
||||
break;
|
||||
case 6:
|
||||
format = DFS_yyMMdd;
|
||||
break;
|
||||
case 7:
|
||||
format = DF_yyyyMM;
|
||||
break;
|
||||
case 8:
|
||||
if (strDate.indexOf("-") != -1) {
|
||||
format = DF_MMddHH;
|
||||
} else {
|
||||
format = DFS_yyyyMMdd;
|
||||
}
|
||||
break;
|
||||
case 10:
|
||||
format = DF_yyyyMMdd;
|
||||
break;
|
||||
case 13:
|
||||
format = DF_yyyyMMddHH;
|
||||
break;
|
||||
case 16:
|
||||
format = DF_yyyyMMddHHmm;
|
||||
break;
|
||||
case 19:
|
||||
format = DF_yyyyMMddHHmmss;
|
||||
break;
|
||||
case 21:
|
||||
format = DF_yyyyMMddHHmmssS;
|
||||
break;
|
||||
default:
|
||||
throw new ParseException("", 0);
|
||||
}
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(format);
|
||||
sdf.setLenient(false);
|
||||
return sdf.parse(strDate);
|
||||
}
|
||||
|
||||
public static Date dayStringToDate(String strDate) {
|
||||
try {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(DF_yyyyMMdd);
|
||||
sdf.setLenient(false);
|
||||
return sdf.parse(strDate);
|
||||
}catch (Exception e){
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><><EFBFBD><EFBFBD><EFBFBD>Date<74><65>String<6E><67>ת<EFBFBD><D7AA><EFBFBD><EFBFBD>formatͨ<74><CDA8>DateUtil.DF_xxx<78><78>4ָ<34><D6B8>
|
||||
*
|
||||
* @param date ת<><D7AA>ǰ<EFBFBD><C7B0><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
* @return String ת<><D7AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
*/
|
||||
public static String dateToStr(Date date, String format) {
|
||||
if (date == null) {
|
||||
return "";
|
||||
}
|
||||
for (int i = 0; i < availableDF.length; i++) {
|
||||
if (availableDF[i].equals(format)) {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(format);
|
||||
sdf.setLenient(false);
|
||||
return sdf.format(date);
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><>ȡdate<74>ĵ<EFBFBD><C4B5><EFBFBD><EFBFBD><EFBFBD>ʼʱ<CABC><CAB1>
|
||||
*
|
||||
* @param date
|
||||
* @return Date
|
||||
*/
|
||||
public static Date getDayStart(Date date) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
}
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static String getDayStartString(Date date) {
|
||||
return getLongDate(getDayStart(date));
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><>ȡdate<74>ĵ<EFBFBD><C4B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1>
|
||||
*
|
||||
* @param date
|
||||
*
|
||||
* @return Date
|
||||
*/
|
||||
public static Date getDayEnd(Date date) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
}
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 23);
|
||||
calendar.set(Calendar.MINUTE, 59);
|
||||
calendar.set(Calendar.SECOND, 59);
|
||||
calendar.set(Calendar.MILLISECOND, calendar.getActualMaximum(Calendar.MILLISECOND) - 1);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static String getDayEndString(Date date) {
|
||||
return getLongDate(getDayEnd(date));
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><>ȡdate<74>ĵ<EFBFBD><C4B5><EFBFBD><EFBFBD><EFBFBD>ʼʱ<CABC><CAB1>
|
||||
*
|
||||
* @param date
|
||||
* @return Date
|
||||
*/
|
||||
public static Date getMonthStart(Date date) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
}
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.set(Calendar.DAY_OF_MONTH, 1);
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><>ȡdate<74>ĵ<EFBFBD><C4B5>µ<EFBFBD><C2B5><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1>
|
||||
*
|
||||
* @param date
|
||||
* @return Date
|
||||
*/
|
||||
public static Date getMonthEnd(Date date) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
}
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 23);
|
||||
calendar.set(Calendar.MINUTE, 59);
|
||||
calendar.set(Calendar.SECOND, 59);
|
||||
calendar.set(Calendar.MILLISECOND, calendar.getActualMaximum(Calendar.MILLISECOND) - 1);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><>ȡdate<74><65><EFBFBD><EFBFBD><EFBFBD>Сʱ<D0A1><CAB1><EFBFBD><EFBFBD>ʼʱ<CABC><CAB1>
|
||||
*
|
||||
* @param date
|
||||
* @return Date
|
||||
*/
|
||||
public static Date getHourStart(Date date) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
}
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
calendar.set(Calendar.MILLISECOND, 0);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><>ȡDate<74><65><EFBFBD>ϻ<EFBFBD><CFBB>ȥ<EFBFBD><C8A5><EFBFBD>պ<EFBFBD><D5BA>Date
|
||||
*
|
||||
* @param date Ҫ<><D2AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
* @param day Ҫ<>ӵ<EFBFBD><D3B5><EFBFBD><EFBFBD><EFBFBD>,<2C><><EFBFBD><EFBFBD>Ϊ<EFBFBD><CEAA><EFBFBD><EFBFBD>,Ϊ<><CEAA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
* @return Date <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
*/
|
||||
public static Date addDate(Date date, int day) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.add(Calendar.DAY_OF_YEAR, day);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><>long<6E>ͳ<EFBFBD><CDB3>ȵ<EFBFBD>ʱ<EFBFBD><CAB1>ת<EFBFBD><D7AA>Ϊ"<22><>ʱ<EFBFBD>w֡<77><D6A1><EFBFBD>"<22>ĸ<EFBFBD>ʽ
|
||||
*/
|
||||
public static String formatTime(long time) {
|
||||
long hour = time / 3600;
|
||||
long tempTime = time % 3600;
|
||||
long min = tempTime / 60;
|
||||
long sec = tempTime % 60;
|
||||
return hour + "ʱ" + min + "<EFBFBD><EFBFBD>" + sec + "<EFBFBD><EFBFBD>";
|
||||
}
|
||||
|
||||
public static Date strToDate(String strDate, String formatStr, String zoneStr) {
|
||||
Locale locale = new Locale(zoneStr);
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(formatStr, locale);
|
||||
Date strtodate = null;
|
||||
try {
|
||||
strtodate = formatter.parse(strDate);
|
||||
} catch (ParseException e) {
|
||||
logger.error(e);
|
||||
|
||||
}
|
||||
return strtodate;
|
||||
}
|
||||
|
||||
public static String getLogTime() {
|
||||
return dateToStr(new Date(), DateUtils.DF_yyyyMMddHHmmss);
|
||||
}
|
||||
|
||||
public static int getIntervalDaysByTwoDate(Date formDate, Date toDate) {
|
||||
int recoupDays = 0;
|
||||
if (formDate != null && toDate != null) {
|
||||
Calendar calendarFrom = Calendar.getInstance();
|
||||
calendarFrom.setTime(formDate);
|
||||
calendarFrom.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendarFrom.set(Calendar.MINUTE, 0);
|
||||
calendarFrom.set(Calendar.SECOND, 0);
|
||||
calendarFrom.set(Calendar.MILLISECOND, 0);
|
||||
|
||||
Calendar calendarTo = Calendar.getInstance();
|
||||
calendarTo.setTime(toDate);
|
||||
calendarTo.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendarTo.set(Calendar.MINUTE, 0);
|
||||
calendarTo.set(Calendar.SECOND, 0);
|
||||
calendarTo.set(Calendar.MILLISECOND, 0);
|
||||
long time = calendarFrom.getTime().getTime() - calendarTo.getTime().getTime();
|
||||
recoupDays = (int) (time / (24 * 3600 * 1000));
|
||||
}
|
||||
return recoupDays;
|
||||
}
|
||||
|
||||
public static String timeStamp2Date(String seconds, String format) {
|
||||
if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
|
||||
return "";
|
||||
}
|
||||
if (format == null || format.isEmpty()) {
|
||||
format = "yyyy-MM-dd HH:mm:ss";
|
||||
}
|
||||
TimeZone timeZone = TimeZone.getTimeZone(DEFAULT_TIME_ZONE);
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(format);
|
||||
sdf.setTimeZone(timeZone);
|
||||
return sdf.format(new Date(Long.valueOf(seconds + "000")));
|
||||
}
|
||||
|
||||
public static String timeStamp2Date(String millisecond) {
|
||||
if (millisecond == null || millisecond.isEmpty() || millisecond.equals("null")) {
|
||||
return "";
|
||||
}
|
||||
TimeZone timeZone = TimeZone.getTimeZone(DEFAULT_TIME_ZONE);
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
sdf.setTimeZone(timeZone);
|
||||
return sdf.format(new Date(Long.valueOf(millisecond)));
|
||||
}
|
||||
|
||||
public static String getTodaySimple(){
|
||||
return LocalDate.now().toString().replace("-","");
|
||||
}
|
||||
public static String getCreateOrderId(String usercode){
|
||||
return usercode+getLongDate(new Date()).replace("-","").replace(":","").replace(" ","").substring(2);
|
||||
}
|
||||
|
||||
public static String toConvertUtcDateStr(Date date){
|
||||
TimeZone tz = TimeZone.getTimeZone(DEFAULT_TIME_ZONE);
|
||||
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
|
||||
df.setTimeZone(tz);
|
||||
return df.format(date);
|
||||
}
|
||||
|
||||
public static String getISO8601TimestampFromDateStr(Date date){
|
||||
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
|
||||
dateFormat.setTimeZone(TimeZone.getTimeZone(DEFAULT_TIME_ZONE));
|
||||
return dateFormat.format(date);
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws ParseException {
|
||||
// Date d = new Date();
|
||||
// System.out.println(getCreateOrderId("1234567"));
|
||||
// System.out.println(DateUtils.getDayStartString(d));
|
||||
// System.out.println(LocalDate.now());
|
||||
System.out.println(DateUtils.dayStringToDate("2020-12-1"));
|
||||
|
||||
System.out.println(DateUtils.getDayEnd(dayStringToDate("2020-12-1")));
|
||||
|
||||
System.out.println("DateUtils.getISO8601TimestampFromDateStr(new Date()) = " +
|
||||
DateUtils.getISO8601TimestampFromDateStr(new Date()));
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
631
comm/Kernel/src/kernel/util/Dom4jUtils.java
Executable file
631
comm/Kernel/src/kernel/util/Dom4jUtils.java
Executable file
@@ -0,0 +1,631 @@
|
||||
package kernel.util;
|
||||
|
||||
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.Reader;
|
||||
import java.io.StringReader;
|
||||
import java.io.StringWriter;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URL;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.parsers.SAXParserFactory;
|
||||
|
||||
import org.dom4j.Attribute;
|
||||
import org.dom4j.Document;
|
||||
import org.dom4j.DocumentException;
|
||||
import org.dom4j.DocumentFactory;
|
||||
import org.dom4j.Element;
|
||||
import org.dom4j.QName;
|
||||
import org.dom4j.io.OutputFormat;
|
||||
import org.dom4j.io.SAXReader;
|
||||
import org.dom4j.io.SAXValidator;
|
||||
import org.dom4j.io.XMLWriter;
|
||||
import org.dom4j.util.XMLErrorHandler;
|
||||
import org.xml.sax.EntityResolver;
|
||||
import org.xml.sax.InputSource;
|
||||
import org.xml.sax.SAXException;
|
||||
import org.xml.sax.XMLReader;
|
||||
|
||||
/**
|
||||
* Dom4j 的一个工具类实现
|
||||
|
||||
* @author
|
||||
* @version 1.0 changed.log 添加一些增删改属性的静态方法
|
||||
*/
|
||||
public abstract class Dom4jUtils {
|
||||
|
||||
public static final String DEFAULT_ENCODING = "GB2312";
|
||||
|
||||
|
||||
public static void validateDocument(Document document, final String xsdName, final InputStream xsdStream)
|
||||
throws SAXException, ParserConfigurationException {
|
||||
// 读取mib-mapping验证文件
|
||||
EntityResolver resolver = new EntityResolver() {
|
||||
public InputSource resolveEntity(String publicId, String systemId) {
|
||||
if (systemId.endsWith(xsdName)) {
|
||||
return new InputSource(xsdStream);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// 创建默认的XML错误处理器
|
||||
XMLErrorHandler errorHandler = new XMLErrorHandler();
|
||||
|
||||
// 获取基于 SAX 的解析器的实例
|
||||
SAXParserFactory factory = SAXParserFactory.newInstance();
|
||||
// 解析器在解析时验证 XML 内容。
|
||||
factory.setValidating(true);
|
||||
// 指定由此代码生成的解析器将提供对 XML 名称空间的支持。
|
||||
factory.setNamespaceAware(true);
|
||||
// 使用当前配置的工厂参数创建 SAXParser 的一个新实例。
|
||||
XMLReader parser = factory.newSAXParser().getXMLReader();
|
||||
parser.setEntityResolver(resolver);
|
||||
parser.setFeature("http://xml.org/sax/features/validation", true);
|
||||
parser.setFeature("http://apache.org/xml/features/validation/schema", true);
|
||||
parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
|
||||
|
||||
// 创建一个SAXValidator校验工具,并设置校验工具的属性
|
||||
SAXValidator validator = new SAXValidator(parser);
|
||||
// 设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。
|
||||
validator.setErrorHandler(errorHandler);
|
||||
// 校验
|
||||
validator.validate(document);
|
||||
|
||||
// 如果错误信息不为空,说明校验失败,打印错误信息
|
||||
if (errorHandler.getErrors().hasContent()) {
|
||||
throw new SAXException(errorHandler.getErrors().asXML());
|
||||
}
|
||||
}
|
||||
|
||||
// public static void validateDocument(Document document) throws SAXException, ParserConfigurationException {
|
||||
//
|
||||
//
|
||||
// // 创建默认的XML错误处理器
|
||||
// XMLErrorHandler errorHandler = new XMLErrorHandler();
|
||||
//
|
||||
// // 获取基于 SAX 的解析器的实例
|
||||
// SAXParserFactory factory = SAXParserFactory.newInstance();
|
||||
// // 解析器在解析时验证 XML 内容。
|
||||
// factory.setValidating(true);
|
||||
// // 指定由此代码生成的解析器将提供对 XML 名称空间的支持。
|
||||
// factory.setNamespaceAware(true);
|
||||
// // 使用当前配置的工厂参数创建 SAXParser 的一个新实例。
|
||||
// XMLReader parser = factory.newSAXParser().getXMLReader();
|
||||
// parser.setEntityResolver(resolver);
|
||||
// parser.setFeature("http://xml.org/sax/features/validation", true);
|
||||
// parser.setFeature("http://apache.org/xml/features/validation/schema", true);
|
||||
// parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
|
||||
//
|
||||
// // 创建一个SAXValidator校验工具,并设置校验工具的属性
|
||||
// SAXValidator validator = new SAXValidator(parser);
|
||||
// // 设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。
|
||||
// validator.setErrorHandler(errorHandler);
|
||||
// // 校验
|
||||
// validator.validate(document);
|
||||
//
|
||||
// // 如果错误信息不为空,说明校验失败,打印错误信息
|
||||
// if (errorHandler.getErrors().hasContent()) {
|
||||
// throw new SAXException(errorHandler.getErrors().asXML());
|
||||
// }
|
||||
// }
|
||||
|
||||
/**
|
||||
* Create dom4j document from xmlSource
|
||||
*
|
||||
* @param xmlSource
|
||||
* Object
|
||||
* @param validate
|
||||
* boolean
|
||||
* @param encoding
|
||||
* String
|
||||
* @throws DocumentException
|
||||
* @throws IOException
|
||||
* @return Document
|
||||
*/
|
||||
public static Document createDOM4jDocument(Object xmlSource, boolean validate, String encoding)
|
||||
throws DocumentException, IOException {
|
||||
// Use xerces and validate XML file
|
||||
Document doc = null;
|
||||
SAXReader saxReader = new SAXReader(true);
|
||||
saxReader.setValidation(validate);
|
||||
if (encoding == null || encoding.equals("")) {
|
||||
encoding = DEFAULT_ENCODING;
|
||||
}
|
||||
|
||||
// Check input source type
|
||||
if (xmlSource instanceof String) {
|
||||
if (((String) xmlSource).startsWith("<")) {
|
||||
// Treat the String as XML code
|
||||
StringReader reader = new StringReader(xmlSource.toString());
|
||||
doc = saxReader.read(reader, encoding);
|
||||
}
|
||||
else {
|
||||
doc = saxReader.read(new File((String) xmlSource));
|
||||
}
|
||||
}
|
||||
else if (xmlSource instanceof File) {
|
||||
doc = saxReader.read((File) xmlSource);
|
||||
}
|
||||
else if (xmlSource instanceof InputStream) {
|
||||
doc = saxReader.read((InputStream) xmlSource);
|
||||
}
|
||||
else if (xmlSource instanceof Reader) {
|
||||
doc = saxReader.read((Reader) xmlSource);
|
||||
}
|
||||
else if (xmlSource instanceof URL) {
|
||||
doc = saxReader.read((URL) xmlSource);
|
||||
}
|
||||
else if (xmlSource instanceof Document) { // 080908 added
|
||||
doc = (Document) xmlSource;
|
||||
}
|
||||
|
||||
return doc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建文档
|
||||
*
|
||||
* @return Document 文档节点
|
||||
* @added by jiayc
|
||||
*/
|
||||
public static Document createDocument() {
|
||||
DocumentFactory factory = new DocumentFactory();
|
||||
Document document = factory.createDocument();
|
||||
return document;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will generate XML file in a StringBuffer based on the given
|
||||
* Dom4j object.
|
||||
*
|
||||
* @param dom4jObj
|
||||
* Object
|
||||
* @param encoding
|
||||
* String
|
||||
* @throws IOException
|
||||
* @return StringBuffer
|
||||
*/
|
||||
public static/* synchronized closed by cxy */StringBuffer generateXMLStringBuffer(Object dom4jObj, String encoding)
|
||||
throws IOException {
|
||||
StringWriter writer = new StringWriter();
|
||||
OutputFormat outformat = OutputFormat.createPrettyPrint();
|
||||
// 设置编码类型
|
||||
if (encoding == null || encoding.trim().equals("")) {
|
||||
encoding = DEFAULT_ENCODING;
|
||||
}
|
||||
outformat.setEncoding(encoding);
|
||||
// dom4j 支持直接输出OBJECT
|
||||
XMLWriter xmlWriter = null;
|
||||
xmlWriter = new XMLWriter(writer, outformat);
|
||||
xmlWriter.write(dom4jObj);
|
||||
xmlWriter.flush();
|
||||
|
||||
return writer.getBuffer();
|
||||
}
|
||||
|
||||
/**
|
||||
* 反射调用DOM4J的某方法,生成BUFFER,不是很有用?只能调一层?
|
||||
*
|
||||
* @param dom4jObj
|
||||
* Object
|
||||
* @param encoding
|
||||
* String
|
||||
* @param className
|
||||
* String
|
||||
* @param methodName
|
||||
* String
|
||||
* @param parameterTypes
|
||||
* Class[]
|
||||
* @param parameterValues
|
||||
* Object[]
|
||||
* @throws IOException
|
||||
* @throws ClassNotFoundException
|
||||
* @throws SecurityException
|
||||
* @throws NoSuchMethodException
|
||||
* @throws IllegalArgumentException
|
||||
* @throws IllegalAccessException
|
||||
* @throws InvocationTargetException
|
||||
* @return StringBuffer
|
||||
*/
|
||||
public static/** synchronized */
|
||||
StringBuffer generateXMLStringBufferByMethodInvoke(Object dom4jObj, String encoding, String className,
|
||||
String methodName, Class<?>[] parameterTypes, Object[] parameterValues) throws IOException,
|
||||
ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException,
|
||||
IllegalAccessException, InvocationTargetException {
|
||||
Class<?> componentClass = null;
|
||||
componentClass = Class.forName(className);
|
||||
Method method;
|
||||
method = componentClass.getMethod(methodName, parameterTypes);
|
||||
Object o = method.invoke(dom4jObj, parameterValues);
|
||||
return generateXMLStringBuffer(o, encoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入节点,不是好方法,可有好方法替代?
|
||||
*
|
||||
* @param parent
|
||||
* Element param insert
|
||||
* @param insertBefore
|
||||
* Element
|
||||
* @return Element
|
||||
*/
|
||||
public static Element insertChild(Element parent, Element toInsert, Element insertBefore) {
|
||||
String str = parent.asXML();
|
||||
String before = insertBefore.asXML();
|
||||
String insert = toInsert.asXML();
|
||||
int pos = -1;
|
||||
if ((pos = str.indexOf(before)) >= 0) {
|
||||
str = str.substring(0, pos) + insert + str.substring(pos);
|
||||
}
|
||||
|
||||
try {
|
||||
parent = Dom4jUtils.createDOM4jDocument(str, false, "").getRootElement();
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
|
||||
return parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入节点,不是好方法,可有好方法替代?
|
||||
*
|
||||
* @param parent
|
||||
* Element param insert
|
||||
* @param insertBefore
|
||||
* Element
|
||||
* @return Element
|
||||
*/
|
||||
public static Element insertChildAfter(Element parent, Element toInsert, Element insertAfter) {
|
||||
String str = parent.asXML();
|
||||
String after = insertAfter.asXML();
|
||||
String insert = toInsert.asXML();
|
||||
int pos = -1;
|
||||
if ((pos = str.indexOf(after)) >= 0) {
|
||||
pos += after.length();
|
||||
str = str.substring(0, pos) + insert + str.substring(pos);
|
||||
}
|
||||
|
||||
try {
|
||||
parent = Dom4jUtils.createDOM4jDocument(str, false, "").getRootElement();
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
|
||||
return parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加新Element节点,值为String类型
|
||||
*
|
||||
* @param parent
|
||||
* 父节点
|
||||
* @param name
|
||||
* 新节点名称
|
||||
* @param value
|
||||
* 新节点值
|
||||
* @return element
|
||||
* @throws XMLDocException
|
||||
*/
|
||||
public static Element appendChild(Element parent, String name, String value) {
|
||||
if (parent == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Element element = parent.addElement(new QName(name, parent.getNamespace()));
|
||||
if (value != null) {
|
||||
element.addText(value);
|
||||
}
|
||||
return element;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除子节点
|
||||
*
|
||||
* @param parent
|
||||
* Element 父节点
|
||||
* @param name
|
||||
* String 删除节点名
|
||||
* @param value
|
||||
* String 删除节点值
|
||||
* @return Element
|
||||
*/
|
||||
public static Element removeChild(Element parent, String name, String value) {
|
||||
if (parent == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Iterator<?> iter = parent.elementIterator();
|
||||
Element del = null;
|
||||
while (iter.hasNext()) {
|
||||
Element tmp = (Element) iter.next();
|
||||
if (tmp.getName().equals(name) && tmp.getText().equals(value)) {
|
||||
del = tmp;
|
||||
}
|
||||
}
|
||||
if (del != null) {
|
||||
parent.remove(del);
|
||||
}
|
||||
return parent;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加属性
|
||||
*
|
||||
* @param ele
|
||||
* Element
|
||||
* @param attributeName
|
||||
* String
|
||||
* @param attributeValue
|
||||
* String
|
||||
* @return Element
|
||||
*/
|
||||
public static Element appendAttribute(Element ele, String attributeName, String attributeValue) {
|
||||
if (ele == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ele.addAttribute(attributeName, attributeValue);
|
||||
return ele;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除属性
|
||||
*
|
||||
* @param ele
|
||||
* Element
|
||||
* @param attributeName
|
||||
* String
|
||||
* @return Element
|
||||
*/
|
||||
public static Element removeAttribute(Element ele, String attributeName) {
|
||||
if (ele == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Attribute att = ele.attribute(attributeName);
|
||||
ele.remove(att);
|
||||
return ele;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改属性
|
||||
*
|
||||
* @param ele
|
||||
* Element
|
||||
* @param attributeName
|
||||
* String
|
||||
* @param attributeValue
|
||||
* String
|
||||
* @return Element
|
||||
*/
|
||||
public static Element setAttribute(Element ele, String attributeName, String attributeValue) {
|
||||
if (ele == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Attribute att = ele.attribute(attributeName);
|
||||
if (att != null) {
|
||||
att.setText(attributeValue);
|
||||
}
|
||||
else {
|
||||
Dom4jUtils.appendAttribute(ele, attributeName, attributeValue);
|
||||
}
|
||||
return ele;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取Element节点下的所有子节点内容,转换成字符串
|
||||
*
|
||||
* @param element
|
||||
* Element
|
||||
* @return String
|
||||
*/
|
||||
public static String getElementContext(Element element) {
|
||||
if (element == null) {
|
||||
return null;
|
||||
}
|
||||
String str = element.getText();
|
||||
for (Iterator<?> i = element.elementIterator(); i.hasNext();) {
|
||||
Element elementTmp = (Element) i.next();
|
||||
str = str + elementTmp.asXML();
|
||||
// do something
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param element
|
||||
* Element
|
||||
* @param path
|
||||
* String
|
||||
* @param attr
|
||||
* String
|
||||
* @return String
|
||||
*/
|
||||
public static String getElementContext(Element element, String path, String attr) {
|
||||
Element el = element.element(path);
|
||||
if (attr == null || attr.trim().equals("")) {
|
||||
return el.getText();
|
||||
}
|
||||
else {
|
||||
return el.attributeValue(attr);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据XPATH 获取元素内容,text。 "/path/@seq" 获取属性值 "/path/" 获取元素
|
||||
*
|
||||
* @param element
|
||||
* Element
|
||||
* @param path
|
||||
* String
|
||||
* @return String
|
||||
*/
|
||||
public static String getElementContext(Element element, String path) {
|
||||
if (element == null || path == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Object o = element.selectSingleNode(path);
|
||||
if (o == null) { // 无此节点
|
||||
return null;
|
||||
}
|
||||
|
||||
if (o instanceof Element) { // 1、元素 Element
|
||||
Element e = (Element) o;
|
||||
if (e.isTextOnly()) { // text only
|
||||
return e.getText();
|
||||
}
|
||||
else { // element
|
||||
try {
|
||||
return Dom4jUtils.generateXMLStringBuffer(e, "").toString();
|
||||
} catch (IOException ex1) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (o instanceof Attribute) { // 2、属性 Attribute
|
||||
return ((Attribute) o).getValue();
|
||||
}
|
||||
else { // 3、其他 Other node
|
||||
try {
|
||||
return Dom4jUtils.generateXMLStringBuffer(o, "").toString();
|
||||
} catch (IOException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据XPATH 获取元素内容,text。 "/path/@seq" 获取属性值 "/path/" 获取元素
|
||||
*
|
||||
* @param element
|
||||
* Element
|
||||
* @param path
|
||||
* String
|
||||
* @return String
|
||||
*/
|
||||
public static String[] getElementContextArray(Element element, String path) {
|
||||
if (element == null || path == null) {
|
||||
return null;
|
||||
}
|
||||
List<?> nodes = element.selectNodes(path);
|
||||
String[] eleContext = new String[nodes.size()];
|
||||
Iterator<?> iter = nodes.iterator();
|
||||
int length = 0;
|
||||
while (iter.hasNext()) {
|
||||
Object o = (Object) iter.next();
|
||||
// Object o = element.selectNodes(path);
|
||||
if (o instanceof Element) { // 1、元素 Element
|
||||
Element e = (Element) o;
|
||||
if (e.isTextOnly()) { // text only
|
||||
// return e.getText();
|
||||
eleContext[length] = e.getText();
|
||||
length++;
|
||||
}
|
||||
else { // element
|
||||
try {
|
||||
eleContext[length] = Dom4jUtils.generateXMLStringBuffer(e, "").toString();
|
||||
length++;
|
||||
// return Dom4jUtil.generateXMLStringBuffer(e,
|
||||
// "").toString();
|
||||
} catch (IOException ex1) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (o instanceof Attribute) { // 2、属性 Attribute
|
||||
// return ( (Attribute) o).getValue();
|
||||
eleContext[length] = ((Attribute) o).getValue();
|
||||
length++;
|
||||
}
|
||||
else { // 3、其他 Other node
|
||||
try {
|
||||
eleContext[length] = Dom4jUtils.generateXMLStringBuffer(o, "").toString();
|
||||
length++;
|
||||
// return Dom4jUtil.generateXMLStringBuffer(o,
|
||||
// "").toString();
|
||||
} catch (IOException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return eleContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加新Element节点,值为String类型
|
||||
*
|
||||
* @param root
|
||||
* 根节点
|
||||
* @param xpath
|
||||
* 新节点路径 eg:/root/a/a1 or /root/b/b1/@seq
|
||||
* @param value
|
||||
* 新节点值
|
||||
* @param isGroup
|
||||
* boolean
|
||||
* @return element
|
||||
*/
|
||||
public static Element appendElement(Element root, String xpath, String value, boolean isGroup) {
|
||||
if (root == null) {
|
||||
return null;
|
||||
}
|
||||
int j = xpath.lastIndexOf("/");
|
||||
String path = xpath.substring(0, j);
|
||||
Element node = (Element) root.selectSingleNode(path);
|
||||
String[] paths = xpath.split("/");
|
||||
if (isGroup) {
|
||||
if (node == null) {
|
||||
for (int i = 2; i < paths.length; i++) {
|
||||
root = root.addElement(new QName(paths[i], root.getNamespace()));
|
||||
}
|
||||
}
|
||||
else {
|
||||
root = node.addElement(new QName(paths[paths.length - 1], root.getNamespace()));
|
||||
}
|
||||
}
|
||||
else {
|
||||
for (int i = 2; i < paths.length; i++) {
|
||||
root = root.addElement(new QName(paths[i], root.getNamespace()));
|
||||
}
|
||||
}
|
||||
|
||||
if (value != null) {
|
||||
root.addText(value);
|
||||
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param args
|
||||
* String[]
|
||||
*/
|
||||
public static void main(String[] args) throws IOException {
|
||||
Document document = Dom4jUtils.createDocument();
|
||||
Element root = document.addElement(new QName("root"));
|
||||
|
||||
Dom4jUtils.appendChild(root, "hi", "hi");
|
||||
Dom4jUtils.appendChild(root, "hi1", "1");
|
||||
Dom4jUtils.appendChild(root, "hi2", "2");
|
||||
|
||||
root.addElement("kaka");
|
||||
|
||||
root = Dom4jUtils.insertChild(root, (Element) root.selectSingleNode("hi1"),
|
||||
(Element) root.selectSingleNode("hi"));
|
||||
root = Dom4jUtils.insertChildAfter(root, (Element) root.selectSingleNode("hi2"),
|
||||
(Element) root.selectSingleNode("hi"));
|
||||
|
||||
System.out.println(Dom4jUtils.generateXMLStringBuffer(root, ""));
|
||||
}
|
||||
}
|
||||
275
comm/Kernel/src/kernel/util/Endecrypt.java
Executable file
275
comm/Kernel/src/kernel/util/Endecrypt.java
Executable file
@@ -0,0 +1,275 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.DESedeKeySpec;
|
||||
|
||||
//jdk7下的加密解密
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
|
||||
//jdk8下的加密解密
|
||||
//import java.util.Base64;
|
||||
/**
|
||||
* <p>
|
||||
* Title:加密解密测试
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Description: 加密解密
|
||||
|
||||
*/
|
||||
public class Endecrypt {
|
||||
/**
|
||||
* 进行MD5加密
|
||||
*
|
||||
* @param String 原始的SPKEY
|
||||
* @return byte[] 指定加密方式为md5后的byte[]
|
||||
*/
|
||||
private byte[] md5(String strSrc) {
|
||||
byte[] returnByte = null;
|
||||
try {
|
||||
MessageDigest md5 = MessageDigest.getInstance("MD5");
|
||||
returnByte = md5.digest(strSrc.getBytes("GBK"));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return returnByte;
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到3-DES的密钥匙 根据接口规范,密钥匙为24个字节,md5加密出来的是16个字节,因此后面补8个字节的0
|
||||
*
|
||||
* @param String 原始的SPKEY
|
||||
* @return byte[] 指定加密方式为md5后的byte[]
|
||||
*/
|
||||
private byte[] getEnKey(String spKey) {
|
||||
byte[] desKey = null;
|
||||
try {
|
||||
byte[] desKey1 = md5(spKey);
|
||||
desKey = new byte[24];
|
||||
int i = 0;
|
||||
while (i < desKey1.length && i < 24) {
|
||||
desKey[i] = desKey1[i];
|
||||
i++;
|
||||
}
|
||||
if (i < 24) {
|
||||
desKey[i] = 0;
|
||||
i++;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return desKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* 3-DES加密
|
||||
*
|
||||
* @param byte[] src 要进行3-DES加密的byte[]
|
||||
* @param byte[] enKey 3-DES加密密钥
|
||||
* @return byte[] 3-DES加密后的byte[]
|
||||
*/
|
||||
public byte[] Encrypt(byte[] src, byte[] enKey) {
|
||||
byte[] encryptedData = null;
|
||||
try {
|
||||
DESedeKeySpec dks = new DESedeKeySpec(enKey);
|
||||
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
|
||||
SecretKey key = keyFactory.generateSecret(dks);
|
||||
Cipher cipher = Cipher.getInstance("DESede");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key);
|
||||
encryptedData = cipher.doFinal(src);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return encryptedData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对字符串进行Base64编码
|
||||
*
|
||||
* @param byte[] src 要进行编码的字符
|
||||
*
|
||||
* @return String 进行编码后的字符串
|
||||
*/
|
||||
public String getBase64Encode(byte[] src) {
|
||||
String requestValue = "";
|
||||
try {
|
||||
// jdk7下的加密解密
|
||||
Base64 base64en = new Base64();
|
||||
requestValue = base64en.encodeAsString(src);
|
||||
// jdk8下的加密解密
|
||||
// requestValue = new String(Base64.getEncoder().encode(src));
|
||||
// System.out.println(requestValue);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return requestValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 去掉字符串的换行符号 base64编码3-DES的数据时,得到的字符串有换行符号 ,一定要去掉,否则uni-wise平台解析票根不会成功,
|
||||
* 提示“sp验证失败”。在开发的过程中,因为这个问题让我束手无策, 一个朋友告诉我可以问联通要一段加密后 的文字,然后去和自己生成的字符串比较,
|
||||
* 这是个不错的调试方法。我最后比较发现我生成的字符串唯一不同的 是多了换行。 我用c#语言也写了票根请求程序,没有发现这个问题。
|
||||
*
|
||||
*/
|
||||
private String filter(String str) {
|
||||
String output = null;
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (int i = 0; i < str.length(); i++) {
|
||||
int asc = str.charAt(i);
|
||||
if (asc != 10 && asc != 13)
|
||||
sb.append(str.subSequence(i, i + 1));
|
||||
}
|
||||
output = new String(sb);
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对字符串进行URLDecoder.encode(strEncoding)编码
|
||||
*
|
||||
* @param String src 要进行编码的字符串
|
||||
*
|
||||
* @return String 进行编码后的字符串
|
||||
*/
|
||||
public String getURLEncode(String src) {
|
||||
String requestValue = "";
|
||||
try {
|
||||
requestValue = URLEncoder.encode(src);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return requestValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 3-DES加密
|
||||
*
|
||||
* @param String src 要进行3-DES加密的String
|
||||
* @param String spkey分配的SPKEY
|
||||
* @return String 3-DES加密后的String
|
||||
*/
|
||||
public String get3DESEncrypt(String src, String spkey) {
|
||||
String requestValue = "";
|
||||
try {
|
||||
// 得到3-DES的密钥匙
|
||||
byte[] enKey = getEnKey(spkey);
|
||||
// 要进行3-DES加密的内容在进行/"UTF-16LE/"取字节
|
||||
byte[] src2 = src.getBytes("UTF-16LE");
|
||||
// 进行3-DES加密后的内容的字节
|
||||
byte[] encryptedData = Encrypt(src2, enKey);
|
||||
// 进行3-DES加密后的内容进行BASE64编码
|
||||
String base64String = getBase64Encode(encryptedData);
|
||||
// BASE64编码去除换行符后
|
||||
String base64Encrypt = filter(base64String);
|
||||
// 对BASE64编码中的HTML控制码进行转义的过程
|
||||
requestValue = getURLEncode(base64Encrypt);
|
||||
// System.out.println(requestValue);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return requestValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对字符串进行URLDecoder.decode(strEncoding)解码
|
||||
*
|
||||
* @param String src 要进行解码的字符串
|
||||
*
|
||||
* @return String 进行解码后的字符串
|
||||
*/
|
||||
public String getURLDecoderdecode(String src) {
|
||||
String requestValue = "";
|
||||
try {
|
||||
requestValue = URLDecoder.decode(src);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return requestValue;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 进行3-DES解密(密钥匙等同于加密的密钥匙)。
|
||||
*
|
||||
* @param byte[] src 要进行3-DES解密byte[]
|
||||
* @param String spkey分配的SPKEY
|
||||
* @return String 3-DES解密后的String
|
||||
*/
|
||||
public String deCrypt(byte[] debase64, String spKey) {
|
||||
String strDe = null;
|
||||
Cipher cipher = null;
|
||||
try {
|
||||
cipher = Cipher.getInstance("DESede");
|
||||
byte[] key = getEnKey(spKey);
|
||||
DESedeKeySpec dks = new DESedeKeySpec(key);
|
||||
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
|
||||
SecretKey sKey = keyFactory.generateSecret(dks);
|
||||
cipher.init(Cipher.DECRYPT_MODE, sKey);
|
||||
byte ciphertext[] = cipher.doFinal(debase64);
|
||||
strDe = new String(ciphertext, "UTF-16LE");
|
||||
} catch (Exception ex) {
|
||||
strDe = "";
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return strDe;
|
||||
}
|
||||
|
||||
/**
|
||||
* 3-DES解密
|
||||
*
|
||||
* @param String src 要进行3-DES解密的String
|
||||
* @param String spkey分配的SPKEY
|
||||
* @return String 3-DES加密后的String
|
||||
*/
|
||||
public String get3DESDecrypt(String src, String spkey) {
|
||||
|
||||
String requestValue = "";
|
||||
try {
|
||||
// 得到3-DES的密钥匙
|
||||
// URLDecoder.decodeTML控制码进行转义的过程
|
||||
String URLValue = getURLDecoderdecode(src);
|
||||
// 进行3-DES加密后的内容进行BASE64编码
|
||||
// jdk7
|
||||
Base64 base64en = new Base64();
|
||||
byte[] base64DValue = base64en.decodeBase64(URLValue);
|
||||
// jdk8
|
||||
// byte[] base64DValue = Base64.getDecoder().decode(URLValue);
|
||||
// 要进行3-DES加密的内容在进行/"UTF-16LE/"取字节
|
||||
requestValue = deCrypt(base64DValue, spkey);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return requestValue;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
Endecrypt test = new Endecrypt();
|
||||
// String oldString = "a1234567";
|
||||
|
||||
String oldString = "1231";
|
||||
// Roj6#@08SDF87323FG00%jjsd
|
||||
String SPKEY = "ew2h2dief3ugyrufhr33d";
|
||||
SPKEY = "Roj6#@08SDF87323FG00%jjsd";
|
||||
oldString = "root";
|
||||
|
||||
System.out.println("1。分配的SPKEY为: " + SPKEY);
|
||||
System.out.println("2。的内容为: " + oldString);
|
||||
String reValue = test.get3DESEncrypt(oldString, SPKEY);
|
||||
reValue = reValue.trim().intern();
|
||||
System.out.println("进行3-DES加密后的内容: " + reValue);
|
||||
|
||||
// oldString = "xpk4ii2rnyR0NsW%2BNNfzSA%3D%3D";
|
||||
// SPKEY = "Roj6#@08SDF87323FG00%jjsd";
|
||||
// String reValue2 = test.get3DESDecrypt(oldString, SPKEY);
|
||||
// System.out.println("进行3-DES解密后的内容: " + reValue2);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
60
comm/Kernel/src/kernel/util/GZIP.java
Executable file
60
comm/Kernel/src/kernel/util/GZIP.java
Executable file
@@ -0,0 +1,60 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
public class GZIP {
|
||||
/**
|
||||
* 字符串的压缩
|
||||
*
|
||||
* @param str
|
||||
* 待压缩的字符串
|
||||
* @return 返回压缩后的字符串
|
||||
* @throws IOException
|
||||
*/
|
||||
public static String compress(String str) throws IOException {
|
||||
if (null == str || str.length() <= 0) {
|
||||
return str;
|
||||
}
|
||||
// 创建一个新的 byte 数组输出流
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
// 使用默认缓冲区大小创建新的输出流
|
||||
GZIPOutputStream gzip = new GZIPOutputStream(out);
|
||||
// 将 b.length 个字节写入此输出流
|
||||
gzip.write(str.getBytes());
|
||||
gzip.close();
|
||||
// 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
|
||||
return out.toString("UTF-8");
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串的解压
|
||||
*
|
||||
* @param str
|
||||
* 对字符串解压
|
||||
* @return 返回解压缩后的字符串
|
||||
* @throws IOException
|
||||
*/
|
||||
public static String unCompress(String str) throws IOException {
|
||||
if (null == str || str.length() <= 0) {
|
||||
return str;
|
||||
}
|
||||
// 创建一个新的 byte 数组输出流
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
// 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组
|
||||
ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes("UTF-8"));
|
||||
// 使用默认缓冲区大小创建新的输入流
|
||||
GZIPInputStream gzip = new GZIPInputStream(in);
|
||||
byte[] buffer = new byte[256];
|
||||
int n = 0;
|
||||
while ((n = gzip.read(buffer)) >= 0) {// 将未压缩数据读入字节数组
|
||||
// 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流
|
||||
out.write(buffer, 0, n);
|
||||
}
|
||||
// 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串
|
||||
return out.toString("UTF-8");
|
||||
}
|
||||
}
|
||||
236
comm/Kernel/src/kernel/util/ImageDispatcher.java
Executable file
236
comm/Kernel/src/kernel/util/ImageDispatcher.java
Executable file
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* 查找图片地址
|
||||
*/
|
||||
package kernel.util;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import kernel.springframework.ServiceLocator;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* @author cwj
|
||||
*
|
||||
*
|
||||
*/
|
||||
public class ImageDispatcher {
|
||||
private final static Logger logger = LoggerFactory.getLogger(ImageDispatcher.class);
|
||||
|
||||
private static boolean startUp;
|
||||
private static String saveDir;
|
||||
private static List viewDirs;
|
||||
//查找缩略图 但是原图片不存在!
|
||||
private static Map<String, String> noFindImgZoom ;
|
||||
private static List noFindImgZoomNeed =new ArrayList();
|
||||
private static List noFindImgZoomSupply=new ArrayList() ;
|
||||
|
||||
private static Properties properties = PropertiesLoaderUtils.loadProperties("config/system.properties");
|
||||
|
||||
//查找图片, 但原图片不存在!
|
||||
private static Map<String, String> noFindImg;
|
||||
|
||||
private static Map<String,String> noFindPerson;
|
||||
|
||||
public static String getSaveDir() {
|
||||
return saveDir;
|
||||
}
|
||||
|
||||
public static void setSaveDir(String saveDir) {
|
||||
ImageDispatcher.saveDir = saveDir;
|
||||
logger.info("[ImageDispatcher setSaveDir] saveDir:{}", saveDir);
|
||||
}
|
||||
|
||||
public static boolean isStartUp() {
|
||||
return startUp;
|
||||
}
|
||||
|
||||
public static void setStartUp(String startUp) {
|
||||
if ("true".equals(startUp)) {
|
||||
ImageDispatcher.startUp = true;
|
||||
} else {
|
||||
ImageDispatcher.startUp = false;
|
||||
}
|
||||
}
|
||||
|
||||
public static List getViewDirs() {
|
||||
return viewDirs;
|
||||
}
|
||||
|
||||
public static void setViewDirs(List viewDirs) {
|
||||
logger.info("[ImageDispatcher setViewDirs] viewDirs:{}", JsonUtils.bean2Json(viewDirs));
|
||||
ImageDispatcher.viewDirs = viewDirs;
|
||||
}
|
||||
|
||||
/**
|
||||
* 响应客户端请求的图片的过滤器处理过程
|
||||
* @param request
|
||||
* @param response
|
||||
* @param filterChain
|
||||
* @throws IOException
|
||||
* @throws ServletException
|
||||
*/
|
||||
public static void doImageFilter(ServletRequest request, ServletResponse response,
|
||||
FilterChain filterChain) throws IOException, ServletException {
|
||||
HttpServletRequest httpReq = (HttpServletRequest) request;
|
||||
HttpServletResponse httpResp = (HttpServletResponse) response;
|
||||
String reqStr = httpReq.getServletPath();
|
||||
FileInputStream imgStream = null;
|
||||
OutputStream toClientStream = null;
|
||||
|
||||
try {
|
||||
File file = findFile(reqStr);
|
||||
if (file != null) {
|
||||
imgStream = new FileInputStream(file);
|
||||
int i = imgStream.available(); //得到文件大小
|
||||
httpResp.setContentType("image/*"); //设置文件类型
|
||||
httpResp.setContentLength(i); //设置文件大小
|
||||
toClientStream = httpResp.getOutputStream(); //得到输出流
|
||||
byte data[] = new byte[1024];
|
||||
//逐步输出数据
|
||||
while( (i = imgStream.read(data)) > 0){
|
||||
toClientStream.write(data,0,i);
|
||||
toClientStream.flush();
|
||||
}
|
||||
} else {
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
} catch(IOException e) {
|
||||
throw e;
|
||||
} finally {
|
||||
if (toClientStream != null) {
|
||||
toClientStream.close();
|
||||
}
|
||||
if (imgStream != null) {
|
||||
imgStream.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从数据库中得到图片地址
|
||||
* @param filePath : /img/2007/10/18/15/T3NHUG4MRO1D.jpg
|
||||
* @return
|
||||
*/
|
||||
public static String getImg(String filePath) {
|
||||
String imgPath = "";
|
||||
if (!StringUtils.isNullOrEmpty(filePath) && filePath.indexOf("http://") != -1) {
|
||||
return filePath;
|
||||
}
|
||||
if (filePath == null) {
|
||||
// if (noFindImg == null || noFindImg.isEmpty()) {
|
||||
// noFindImg = new HashMap<String, String>();
|
||||
// noFindImg.put("1", "../sysImg/no-find-1.jpg");
|
||||
// noFindImg.put("2", "../sysImg/no-find-2.jpg");
|
||||
// noFindImg.put("3", "../sysImg/no-find-3.jpg");
|
||||
// }
|
||||
// imgPath = noFindImg.get(type);
|
||||
// return imgPath;
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
File file = ImageDispatcher.findFile(filePath);
|
||||
if (file == null) {
|
||||
//原图片不存在!
|
||||
return null;
|
||||
} else {
|
||||
imgPath = ServiceLocator.getMessage("http.server.host") + filePath;
|
||||
}
|
||||
return imgPath;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 根据相对路径查找真实路径,如果不存在返回空
|
||||
* @return
|
||||
*/
|
||||
public static File findFile(String absPath) {
|
||||
File file = null;
|
||||
if (startUp && saveDir != null) {
|
||||
file = new File(saveDir + absPath);
|
||||
if (file.isFile()) {
|
||||
return file;
|
||||
} else if (viewDirs != null) {
|
||||
for (Iterator it = viewDirs.iterator(); it.hasNext(); ) {
|
||||
file = new File((String)it.next() + absPath);
|
||||
if (file.isFile()) {
|
||||
return file;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
file = new File(properties.getProperty("images.dir") + absPath);
|
||||
if (file.isFile()) {
|
||||
return file;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Map<String, String> getNoFindImgZoom() {
|
||||
return noFindImgZoom;
|
||||
}
|
||||
public static void setNotFindImgZoom(Map<String, String> noFindImgZoom) {
|
||||
ImageDispatcher.noFindImgZoom = noFindImgZoom;
|
||||
}
|
||||
|
||||
public static Map<String, String> getNoFindImg() {
|
||||
return noFindImg;
|
||||
}
|
||||
public static void setNoFindImg(Map<String, String> noFindImg) {
|
||||
ImageDispatcher.noFindImg = noFindImg;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除一张原图
|
||||
* @param filePath
|
||||
*/
|
||||
public static void delFile(String filePath){
|
||||
File file = findFile(filePath);
|
||||
if(file != null){
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// //System.out.println(ImageDispatcher.getNotImage());2007/10/18/15/T3NHUG4MRO1D.jpg
|
||||
// //System.out.println(ImageDispatcher.getImgZoom("", "2"));
|
||||
// //System.out.println(ImageDispatcher.getImg("", "2"));
|
||||
ImageDispatcher.delFile("2007/10/18/20/PT517L1U6841.jpg");
|
||||
|
||||
}
|
||||
|
||||
public static List getNoFindImgZoomNeed() {
|
||||
return noFindImgZoomNeed;
|
||||
}
|
||||
|
||||
public static void setNoFindImgZoomNeed(List noFindImgZoomNeed) {
|
||||
ImageDispatcher.noFindImgZoomNeed = noFindImgZoomNeed;
|
||||
}
|
||||
|
||||
public static List getNoFindImgZoomSupply() {
|
||||
return noFindImgZoomSupply;
|
||||
}
|
||||
|
||||
public static void setNoFindImgZoomSupply(List noFindImgZoomSupply) {
|
||||
ImageDispatcher.noFindImgZoomSupply = noFindImgZoomSupply;
|
||||
}
|
||||
|
||||
}
|
||||
198
comm/Kernel/src/kernel/util/ImageUtils.java
Executable file
198
comm/Kernel/src/kernel/util/ImageUtils.java
Executable file
@@ -0,0 +1,198 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.awt.Graphics;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
|
||||
import java.awt.Image;
|
||||
|
||||
public class ImageUtils {
|
||||
/**
|
||||
* 图片合成
|
||||
*
|
||||
* @param backgroundPath 底图
|
||||
* @param smallPath 小图
|
||||
* @param type 生成图片类型jpg,png...
|
||||
* @param resultPaht 生成图片保存路径
|
||||
*/
|
||||
public static void image(String backgroundPath, String smallPath, String type, String resultPaht) {
|
||||
try {
|
||||
Assert.hasText(backgroundPath, "底图路径为空");
|
||||
Assert.hasText(smallPath, "小图路径为空");
|
||||
BufferedImage small = getBufferedImageFromUrl(smallPath);
|
||||
BufferedImage image = getBufferedImageFromUrl(backgroundPath);
|
||||
// 生成画笔
|
||||
Graphics g = image.getGraphics();
|
||||
g.drawImage(small, image.getWidth() - small.getWidth(), image.getHeight() - small.getHeight(),
|
||||
image.getWidth(), image.getHeight(), null);
|
||||
ImageIO.write(image, type, new File(resultPaht));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("合成图片失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void image_usercode(String backgroundPath, String smallPath, String type, String resultPaht) {
|
||||
try {
|
||||
Assert.hasText(backgroundPath, "底图路径为空");
|
||||
Assert.hasText(smallPath, "小图路径为空");
|
||||
BufferedImage small = getBufferedImageFromUrl(smallPath);
|
||||
BufferedImage image = getBufferedImageFromUrl(backgroundPath);
|
||||
// 生成画笔
|
||||
Graphics g = image.getGraphics();
|
||||
int x = (int) Arith.sub(Arith.div(image.getWidth(), 2), 92);
|
||||
int y = (int) Arith.sub(image.getHeight(), Arith.add(small.getHeight(), 92));
|
||||
g.drawImage(small, x, y, small.getWidth(), small.getHeight(), null);
|
||||
ImageIO.write(image, type, new File(resultPaht));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("合成图片失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据图片url获取图片
|
||||
*
|
||||
* @param url
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
private static BufferedImage getBufferedImageFromUrl(String url) throws IOException {
|
||||
if (url.startsWith("https://") || url.startsWith("http://")) {
|
||||
return ImageIO.read(new URL(url));
|
||||
} else {
|
||||
return ImageIO.read(new File(url));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 合成图片并返回base64字符串
|
||||
*
|
||||
*/
|
||||
public static String image_usercodeBase64(String backgroundPath, String smallPath, String type, String resultPaht) {
|
||||
try {
|
||||
Assert.hasText(backgroundPath, "底图路径为空");
|
||||
Assert.hasText(smallPath, "小图路径为空");
|
||||
BufferedImage small = getBufferedImageFromUrl(smallPath);
|
||||
BufferedImage image = getBufferedImageFromUrl(backgroundPath);
|
||||
// 生成画笔
|
||||
Graphics g = image.getGraphics();
|
||||
int x = (int) Arith.sub(Arith.div(image.getWidth(), 2), 92);
|
||||
int y = (int) Arith.sub(image.getHeight(), Arith.add(small.getHeight(), 40));
|
||||
|
||||
g.drawImage(small, x, y, small.getWidth(), small.getHeight(), null);
|
||||
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ImageIO.write(image, type, outputStream);
|
||||
String data = DatatypeConverter.printBase64Binary(outputStream.toByteArray());
|
||||
|
||||
return data;
|
||||
|
||||
// ImageIO.write(image, type, new File(resultPaht));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("合成图片失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件转 base64
|
||||
* @param file
|
||||
* @return
|
||||
*/
|
||||
public static String file2Base64(File file) {
|
||||
if (file == null) {
|
||||
return null;
|
||||
}
|
||||
String base64 = null;
|
||||
FileInputStream fin = null;
|
||||
try {
|
||||
fin = new FileInputStream(file);
|
||||
byte[] buff = new byte[fin.available()];
|
||||
fin.read(buff);
|
||||
base64 = Base64.encode(buff);
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (fin != null) {
|
||||
try {
|
||||
fin.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return base64;
|
||||
}
|
||||
|
||||
/**
|
||||
* 指定图片宽度和高度或压缩比例对图片进行压缩
|
||||
* @param file 文件
|
||||
* @param rate 压缩比例(为空或者1,原比例压缩)
|
||||
*/
|
||||
public static String reduceImg(File file,Float rate) throws Exception {
|
||||
String res = "";
|
||||
File srcfile = file;
|
||||
int widthdist = 0, heightdist = 0;
|
||||
// 检查图片文件是否存在
|
||||
// Float rate = null;
|
||||
// rate = 1f;
|
||||
// System.out.println(file.length());
|
||||
// 如果比例不为空则说明是按比例压缩
|
||||
if (rate != null && rate > 0) {
|
||||
// 获得源图片的宽高存入数组中
|
||||
int[] results = getImgWidthHeight(srcfile);
|
||||
if (results == null || results[0] == 0 || results[1] == 0) {
|
||||
return "";
|
||||
} else {
|
||||
// 按比例缩放或扩大图片大小,将浮点型转为整型
|
||||
widthdist = (int) (results[0] * rate);
|
||||
heightdist = (int) (results[1] * rate);
|
||||
}
|
||||
}
|
||||
// 开始读取文件并进行压缩
|
||||
Image src = ImageIO.read(srcfile);
|
||||
|
||||
// 构造一个类型为预定义图像类型之一的 BufferedImage
|
||||
BufferedImage tag = new BufferedImage((int) widthdist, (int) heightdist, BufferedImage.TYPE_INT_RGB);
|
||||
|
||||
// 绘制图像 getScaledInstance表示创建此图像的缩放版本,返回一个新的缩放版本Image,按指定的width,height呈现图像
|
||||
// Image.SCALE_SMOOTH,选择图像平滑度比缩放速度具有更高优先级的图像缩放算法。
|
||||
tag.getGraphics().drawImage(src.getScaledInstance(widthdist, heightdist, Image.SCALE_SMOOTH), 0, 0, null);
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
ImageIO.write(tag, "jpg", outputStream);
|
||||
String base64Img = Base64.encode(outputStream.toByteArray());
|
||||
res = "data:image/jpg;base64," + base64Img.toString();
|
||||
outputStream.close();
|
||||
// 创建文件输出流
|
||||
return res;
|
||||
}
|
||||
public static int[] getImgWidthHeight(File file) {
|
||||
InputStream is = null;
|
||||
BufferedImage src = null;
|
||||
int result[] = { 0, 0 };
|
||||
try {
|
||||
// 获得文件输入流
|
||||
is = new FileInputStream(file);
|
||||
// 从流里将图片写入缓冲图片区
|
||||
src = ImageIO.read(is);
|
||||
result[0] = src.getWidth(null); // 得到源图片宽
|
||||
result[1] = src.getHeight(null);// 得到源图片高
|
||||
is.close(); // 关闭输入流
|
||||
} catch (Exception ef) {
|
||||
ef.printStackTrace();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
161
comm/Kernel/src/kernel/util/ImageVerificationCodeUtil.java
Executable file
161
comm/Kernel/src/kernel/util/ImageVerificationCodeUtil.java
Executable file
@@ -0,0 +1,161 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Random;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
|
||||
public class ImageVerificationCodeUtil {
|
||||
private int weight = 100; // 验证码图片的长和宽
|
||||
private int height = 40;
|
||||
private String text; // 用来保存验证码的文本内容
|
||||
private Random r = new Random(); // 获取随机数对象
|
||||
// private String[] fontNames = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
|
||||
// //字体数组
|
||||
// 字体数组
|
||||
private String[] fontNames = { "Georgia" };
|
||||
// 验证码数组
|
||||
private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
|
||||
// private String codes = "用来保存验证码的文本内容";
|
||||
|
||||
/**
|
||||
* 获取随机的颜色
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private Color randomColor() {
|
||||
int r = this.r.nextInt(225); // 这里为什么是225,因为当r,g,b都为255时,即为白色,为了好辨认,需要颜色深一点。
|
||||
int g = this.r.nextInt(225);
|
||||
int b = this.r.nextInt(225);
|
||||
return new Color(r, g, b); // 返回一个随机颜色
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取随机字体
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private Font randomFont() {
|
||||
int index = r.nextInt(fontNames.length); // 获取随机的字体
|
||||
String fontName = fontNames[index];
|
||||
int style = r.nextInt(4); // 随机获取字体的样式,0是无样式,1是加粗,2是斜体,3是加粗加斜体
|
||||
int size = r.nextInt(10) + 24; // 随机获取字体的大小
|
||||
return new Font(fontName, style, size); // 返回一个随机的字体
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取随机字符
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private char randomChar() {
|
||||
int index = r.nextInt(codes.length());
|
||||
return codes.charAt(index);
|
||||
}
|
||||
|
||||
/**
|
||||
* 画干扰线,验证码干扰线用来防止计算机解析图片
|
||||
*
|
||||
* @param image
|
||||
*/
|
||||
private void drawLine(BufferedImage image) {
|
||||
int num = 5 + r.nextInt(10); // 定义干扰线的数量
|
||||
Graphics2D g = (Graphics2D) image.getGraphics();
|
||||
for (int i = 0; i < num; i++) {
|
||||
int x1 = r.nextInt(weight);
|
||||
int y1 = r.nextInt(height);
|
||||
int x2 = r.nextInt(weight);
|
||||
int y2 = r.nextInt(height);
|
||||
g.setColor(randomColor());
|
||||
g.drawLine(x1, y1, x2, y2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建图片的方法
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private BufferedImage createImage() {
|
||||
// 创建图片缓冲区
|
||||
BufferedImage image = new BufferedImage(weight, height, BufferedImage.TYPE_INT_RGB);
|
||||
// 获取画笔
|
||||
Graphics2D g = (Graphics2D) image.getGraphics();
|
||||
// 设置背景色随机
|
||||
g.setColor(new Color(255, 255, r.nextInt(245) + 10));
|
||||
g.fillRect(0, 0, weight, height);
|
||||
// 返回一个图片
|
||||
return image;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取验证码图片的方法
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public BufferedImage getImage() {
|
||||
BufferedImage image = createImage();
|
||||
Graphics2D g = (Graphics2D) image.getGraphics(); // 获取画笔
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < 4; i++) // 画四个字符即可
|
||||
{
|
||||
String s = randomChar() + ""; // 随机生成字符,因为只有画字符串的方法,没有画字符的方法,所以需要将字符变成字符串再画
|
||||
sb.append(s); // 添加到StringBuilder里面
|
||||
float x = i * 1.0F * weight / 4; // 定义字符的x坐标
|
||||
g.setFont(randomFont()); // 设置字体,随机
|
||||
g.setColor(randomColor()); // 设置颜色,随机
|
||||
g.drawString(s, x, height - 5);
|
||||
}
|
||||
this.text = sb.toString();
|
||||
drawLine(image);
|
||||
return image;
|
||||
}
|
||||
|
||||
public String getBase64() {
|
||||
BufferedImage image = this.getImage();
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
try {
|
||||
ImageIO.write(image, "JPEG", outputStream);
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
String data = "data:image/jpg;base64," + DatatypeConverter.printBase64Binary(outputStream.toByteArray());
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取验证码文本的方法
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public static void output(BufferedImage image, OutputStream out) throws IOException // 将验证码图片写出的方法
|
||||
{
|
||||
ImageIO.write(image, "JPEG", out);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ImageVerificationCodeUtil ivc = new ImageVerificationCodeUtil(); // 用我们的验证码类,生成验证码类对象
|
||||
BufferedImage image = ivc.getImage(); // 获取验证码
|
||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||
try {
|
||||
ImageIO.write(image, "JPEG", outputStream);
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
String data = "data:image/jpg;base64," + DatatypeConverter.printBase64Binary(outputStream.toByteArray());
|
||||
// System.out.println(data);
|
||||
}
|
||||
}
|
||||
70
comm/Kernel/src/kernel/util/ImageVerificationEndecrypt.java
Executable file
70
comm/Kernel/src/kernel/util/ImageVerificationEndecrypt.java
Executable file
@@ -0,0 +1,70 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.security.Key;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
public class ImageVerificationEndecrypt {
|
||||
/**
|
||||
* 加密数据
|
||||
*
|
||||
* @param encryptString 注意:这里的数据长度只能为8的倍数
|
||||
* @param encryptKey
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String encryptDES(String encryptString, String encryptKey) throws Exception {
|
||||
SecretKeySpec key = new SecretKeySpec(getKey(encryptKey), "DES");
|
||||
// Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
|
||||
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key);
|
||||
byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
|
||||
return ConvertUtil.bytesToHexString(encryptedData);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义一个key
|
||||
*
|
||||
* @param string
|
||||
*/
|
||||
public static byte[] getKey(String keyRule) {
|
||||
Key key = null;
|
||||
byte[] keyByte = keyRule.getBytes();
|
||||
// 创建一个空的八位数组,默认情况下为0
|
||||
byte[] byteTemp = new byte[8];
|
||||
// 将用户指定的规则转换成八位数组
|
||||
for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
|
||||
byteTemp[i] = keyByte[i];
|
||||
}
|
||||
key = new SecretKeySpec(byteTemp, "DES");
|
||||
return key.getEncoded();
|
||||
}
|
||||
|
||||
/***
|
||||
* 解密数据
|
||||
*
|
||||
* @param decryptString
|
||||
* @param decryptKey
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String decryptDES(String decryptString, String decryptKey) throws Exception {
|
||||
SecretKeySpec key = new SecretKeySpec(getKey(decryptKey), "DES");
|
||||
// Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
|
||||
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, key);
|
||||
byte decryptedData[] = cipher.doFinal(ConvertUtil.hexStringToByte(decryptString));
|
||||
return new String(decryptedData);
|
||||
}
|
||||
|
||||
// public static void main(String[] args) throws Exception {
|
||||
// String clearText = "spri"; // 这里的数据长度必须为8的倍数
|
||||
// String key = "12345678image_key";
|
||||
// System.out.println("明文:" + clearText + "\n密钥:" + key);
|
||||
// String encryptText = encryptDES(clearText, key);
|
||||
// System.out.println("加密后:" + encryptText);
|
||||
// String decryptText = decryptDES(encryptText, key);
|
||||
// System.out.println("解密后:" + decryptText);
|
||||
// }
|
||||
}
|
||||
136
comm/Kernel/src/kernel/util/JsonUtils.java
Executable file
136
comm/Kernel/src/kernel/util/JsonUtils.java
Executable file
@@ -0,0 +1,136 @@
|
||||
package kernel.util;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import org.codehaus.jackson.JsonNode;
|
||||
import org.codehaus.jackson.JsonParser.Feature;
|
||||
import org.codehaus.jackson.map.DeserializationConfig;
|
||||
import org.codehaus.jackson.map.ObjectMapper;
|
||||
import org.codehaus.jackson.type.TypeReference;
|
||||
|
||||
/**
|
||||
*
|
||||
* <p>
|
||||
* Title:
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Description:json工具類
|
||||
* </p>
|
||||
|
||||
*/
|
||||
public class JsonUtils {
|
||||
/**
|
||||
* 转成JSON字符串
|
||||
*
|
||||
* @param obj
|
||||
* @return
|
||||
*/
|
||||
public static String getJsonString(Object obj) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
try {
|
||||
return mapper.writeValueAsString(obj);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param <T>
|
||||
* @param jsonStr
|
||||
* @param T
|
||||
* @return
|
||||
*/
|
||||
public static <T> T readJsonEntity(String jsonStr, Class<T> T) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
try {
|
||||
mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
|
||||
return mapper.readValue(jsonStr, T);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JsonNode
|
||||
*
|
||||
* @param jsonStr
|
||||
* @see { 代码示例: String resultJson
|
||||
* ="{'playerResults':[{'playerId':'111','gameId':'','tee':'0,0,0'},{'playerId':'ff80808137f7daac0137f7dd1ab80001','gameId':'','tee':'255,255,255'}]}";
|
||||
* JsonNode jn=readJsonEntity(resultJson); jn=jn.get("playerResults");
|
||||
* for (int i = 0; i < jn.size(); i++){ String
|
||||
* playerId=jn.get(i).get("playerId").asText();
|
||||
* logger.info("playerId="+playerId); } }
|
||||
* @return
|
||||
*/
|
||||
public static JsonNode readJsonEntity(String jsonStr) {
|
||||
return readJsonEntity(jsonStr, JsonNode.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将POJO转换成JSON
|
||||
* @param object
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String bean2Json(Object object) {
|
||||
if (object == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String json = null;
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
try {
|
||||
json = mapper.writeValueAsString(object);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将JSON转换成POJO
|
||||
* @param <T>
|
||||
* @param json
|
||||
* @param beanClz POJO的Class
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static <T> T json2Object(String json, Class<T> beanClz) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
|
||||
mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
|
||||
mapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
|
||||
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
T t = null;
|
||||
try {
|
||||
t = mapper.readValue(json, beanClz);
|
||||
} catch (Exception e) {
|
||||
try {t = beanClz.newInstance();} catch (Exception e1) {}
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* json数组转List
|
||||
* @param jsonStr
|
||||
* @param valueTypeRef
|
||||
* @return
|
||||
*/
|
||||
public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef) {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
try {
|
||||
return objectMapper.readValue(jsonStr, valueTypeRef);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
87
comm/Kernel/src/kernel/util/MyEmojiUtil.java
Executable file
87
comm/Kernel/src/kernel/util/MyEmojiUtil.java
Executable file
@@ -0,0 +1,87 @@
|
||||
package kernel.util;
|
||||
|
||||
import cn.hutool.extra.emoji.EmojiUtil;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class MyEmojiUtil {
|
||||
|
||||
|
||||
private static boolean isSpecialCharacter(char codePoint) {
|
||||
return (codePoint == 0x0) ||
|
||||
(codePoint == 0x9) ||
|
||||
(codePoint == 0xA) ||
|
||||
(codePoint == 0xD) ||
|
||||
((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
|
||||
((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
|
||||
((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
|
||||
}
|
||||
|
||||
public static boolean containsSpecialCharacter(String source) {
|
||||
if (StringUtils.isBlank(source)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int len = source.length();
|
||||
|
||||
for (int i = 0; i < len; i++) {
|
||||
char codePoint = source.charAt(i);
|
||||
|
||||
if (isSpecialCharacter(codePoint)) {
|
||||
//do nothing,判断到了这里表明,确认有表情字符
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public static boolean containsEmoji(String source) {
|
||||
if(EmojiUtil.containsEmoji(source)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return containsSpecialCharacter(source);
|
||||
}
|
||||
|
||||
/*
|
||||
* 文本转unicode编码
|
||||
*/
|
||||
public static String gbEncoding(final String gbString) {
|
||||
char[] utfBytes = gbString.toCharArray();
|
||||
String unicodeBytes = "";
|
||||
for (int i = 0; i < utfBytes.length; i++) {
|
||||
String hexB = Integer.toHexString(utfBytes[i]);
|
||||
if (hexB.length() <= 2) {
|
||||
hexB = "00" + hexB;
|
||||
}
|
||||
unicodeBytes = unicodeBytes + "\\u" + hexB;
|
||||
}
|
||||
return unicodeBytes;
|
||||
}
|
||||
/*
|
||||
* unicode编码还原
|
||||
*/
|
||||
public static String decodeUnicode(final String dataStr) {
|
||||
if(dataStr==null||!dataStr.startsWith("\\u")) {
|
||||
return dataStr;
|
||||
}
|
||||
int start = 0;
|
||||
int end = 0;
|
||||
final StringBuffer buffer = new StringBuffer();
|
||||
while (start > -1) {
|
||||
end = dataStr.indexOf("\\u", start + 2);
|
||||
String charStr = "";
|
||||
if (end == -1) {
|
||||
charStr = dataStr.substring(start + 2, dataStr.length());
|
||||
} else {
|
||||
charStr = dataStr.substring(start + 2, end);
|
||||
}
|
||||
char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
|
||||
buffer.append(new Character(letter).toString());
|
||||
start = end;
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
}
|
||||
291
comm/Kernel/src/kernel/util/NumberUtils.java
Executable file
291
comm/Kernel/src/kernel/util/NumberUtils.java
Executable file
@@ -0,0 +1,291 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.BigInteger;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* 提供高精度的运算支持.
|
||||
* 所以函数以double为参数类型,兼容int与float.
|
||||
*
|
||||
*/
|
||||
public abstract class NumberUtils extends org.springframework.util.NumberUtils {
|
||||
|
||||
/**
|
||||
* 精确的加法运算.
|
||||
*/
|
||||
public static double add(double v1, double v2) {
|
||||
BigDecimal b1 = new BigDecimal(v1);
|
||||
BigDecimal b2 = new BigDecimal(v2);
|
||||
return b1.add(b2).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 精确的减法运算.
|
||||
*
|
||||
* @param v1 被减数
|
||||
* @param v2 减数
|
||||
*/
|
||||
public static double subtract(double v1, double v2) {
|
||||
BigDecimal b1 = new BigDecimal(Double.toString(v1));
|
||||
BigDecimal b2 = new BigDecimal(Double.toString(v2));
|
||||
return b1.subtract(b2).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供精确的乘法运算.
|
||||
*/
|
||||
public static double multiply(double v1, double v2) {
|
||||
BigDecimal b1 = new BigDecimal(v1);
|
||||
BigDecimal b2 = new BigDecimal(v2);
|
||||
return b1.multiply(b2).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供精确的乘法运算,并对运算结果截位.
|
||||
*
|
||||
* @param scale 运算结果小数后精确的位数
|
||||
*/
|
||||
public static double multiply(double v1, double v2, int scale) {
|
||||
if (scale < 0) {
|
||||
throw new IllegalArgumentException("The scale must be a positive integer or zero");
|
||||
}
|
||||
BigDecimal b1 = new BigDecimal(v1);
|
||||
BigDecimal b2 = new BigDecimal(v2);
|
||||
return b1.multiply(b2).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供(相对)精确的除法运算.
|
||||
*
|
||||
* @see #divide(double, double, int)
|
||||
*/
|
||||
public static double divide(double v1, double v2) {
|
||||
BigDecimal b1 = new BigDecimal(v1);
|
||||
BigDecimal b2 = new BigDecimal(v2);
|
||||
return b1.divide(b2).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供(相对)精确的除法运算.
|
||||
* 由scale参数指定精度,以后的数字四舍五入.
|
||||
*
|
||||
* @param v1 被除数
|
||||
* @param v2 除数
|
||||
* @param scale 表示表示需要精确到小数点以后几位
|
||||
*/
|
||||
public static double divide(double v1, double v2, int scale) {
|
||||
if (scale < 0) {
|
||||
throw new IllegalArgumentException("The scale must be a positive integer or zero");
|
||||
}
|
||||
|
||||
BigDecimal b1 = new BigDecimal(v1);
|
||||
BigDecimal b2 = new BigDecimal(v2);
|
||||
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供精确的小数位四舍五入处理.
|
||||
*
|
||||
* @param v 需要四舍五入的数字
|
||||
* @param scale 小数点后保留几位
|
||||
*/
|
||||
public static double round(double v, int scale) {
|
||||
if (scale < 0) {
|
||||
throw new IllegalArgumentException("The scale must be a positive integer or zero");
|
||||
}
|
||||
BigDecimal b = new BigDecimal(v);
|
||||
return b.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
|
||||
}
|
||||
|
||||
public static int compare(Number left, Number right) throws IllegalArgumentException {
|
||||
Assert.notNull(left, "left number must not be null");
|
||||
Assert.notNull(right, "right number must not be null");
|
||||
|
||||
if (left.getClass().equals(Byte.class)) {
|
||||
return ((Byte) left).compareTo((Byte) right);
|
||||
}
|
||||
else if (left.getClass().equals(Short.class)) {
|
||||
return ((Short) left).compareTo((Short) right);
|
||||
}
|
||||
else if (left.getClass().equals(Integer.class)) {
|
||||
return ((Integer) left).compareTo((Integer) right);
|
||||
}
|
||||
else if (left.getClass().equals(Long.class)) {
|
||||
return ((Long) left).compareTo((Long) right);
|
||||
}
|
||||
else if (left.getClass().equals(BigInteger.class)) {
|
||||
return ((BigInteger) left).compareTo((BigInteger) right);
|
||||
}
|
||||
else if (left.getClass().equals(Float.class)) {
|
||||
return ((Float) left).compareTo((Float) right);
|
||||
}
|
||||
else if (left.getClass().equals(Double.class)) {
|
||||
return ((Double) left).compareTo((Double) right);
|
||||
}
|
||||
else if (left.getClass().equals(BigDecimal.class)) {
|
||||
return ((BigDecimal) left).compareTo((BigDecimal) right);
|
||||
}
|
||||
else {
|
||||
throw new IllegalArgumentException("Could not compare left number [" + left + "] of type ["
|
||||
+ left.getClass().getName() + "] to right number [" + right + "] of type ["
|
||||
+ right.getClass().getName() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
public static int safeLongToInt(long l) {
|
||||
if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
|
||||
throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
|
||||
}
|
||||
return (int) l;
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD>ʽ<EFBFBD><CABD>Ϊ<EFBFBD><CEAA>Ǯ<EFBFBD><C7AE>ʽ
|
||||
*
|
||||
* @param number
|
||||
* <20><><EFBFBD>ʽ<EFBFBD><CABD><EFBFBD><EFBFBD>BigDecimal
|
||||
* @return С<><D0A1><EFBFBD><EFBFBD>2λ<32><CEBB>ʽ<EFBFBD><CABD><EFBFBD>ַ<EFBFBD>
|
||||
*/
|
||||
public static String formatNumericFee(BigDecimal number) {
|
||||
return number.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD>ʽ<EFBFBD><CABD>Ϊ<EFBFBD><CEAA><EFBFBD><7F>ʽ
|
||||
*
|
||||
* @param number
|
||||
* <20><><EFBFBD>ʽ<EFBFBD><CABD><EFBFBD><EFBFBD>BigDecimal
|
||||
* @return С<><D0A1><EFBFBD><EFBFBD>6λ<36><CEBB>ʽ<EFBFBD><CABD><EFBFBD>ַ<EFBFBD>
|
||||
*/
|
||||
public static String formatNumericTraffic(BigDecimal number) {
|
||||
return number.setScale(6, BigDecimal.ROUND_HALF_UP).toString();
|
||||
}
|
||||
|
||||
// <20><><EFBFBD>һ<EFBFBD><D2BB>ת<EFBFBD><D7AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>bigdecimalת<6C><D7AA>ΪTB<54><42>GB<47><42>MB<4D><42><EFBFBD><EFBFBD>ʽ
|
||||
public static String mbToTGM(BigDecimal mb) {
|
||||
StringBuffer sb = new StringBuffer(200);
|
||||
int g = 0;
|
||||
int t = 0;
|
||||
BigDecimal m = new BigDecimal(0);
|
||||
|
||||
t = new Float(mb.divide(new BigDecimal(1024 * 1024), BigDecimal.ROUND_DOWN).floatValue()).intValue();
|
||||
mb = mb.subtract((new BigDecimal(t).multiply(new BigDecimal(1024 * 1024))));
|
||||
g = new Float(mb.divide(new BigDecimal(1024), BigDecimal.ROUND_DOWN).floatValue()).intValue();
|
||||
mb = mb.subtract((new BigDecimal(g).multiply(new BigDecimal(1024))));
|
||||
m = mb.setScale(2, BigDecimal.ROUND_HALF_UP);
|
||||
|
||||
sb.append(new Integer(t).toString()).append(" TB ");
|
||||
|
||||
sb.append(new Integer(g).toString()).append(" GB ");
|
||||
|
||||
sb.append(m.toString()).append(" MB ");
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
// <20><>value<75><65>ǰ4<C7B0><34><EFBFBD>ֽڶs<DAB6><73><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
public static Integer readInt(byte[] value) {
|
||||
if (value == null || value.length < 4) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(value);
|
||||
DataInputStream dis = new DataInputStream(bais);
|
||||
Integer retval = dis.readInt();
|
||||
bais.close();
|
||||
dis.close();
|
||||
return retval;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// <20><>value<75><65>ǰ}<7D><><EFBFBD>ֽڶs<DAB6><73><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
public static Short readShort(byte[] value) {
|
||||
if (value == null || value.length < 2) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
ByteArrayInputStream bais = new ByteArrayInputStream(value);
|
||||
DataInputStream dis = new DataInputStream(bais);
|
||||
Short retval = dis.readShort();
|
||||
bais.close();
|
||||
dis.close();
|
||||
return retval;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] intToByteArray(Integer value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
byte[] data = null;
|
||||
ByteArrayOutputStream bais = new ByteArrayOutputStream(4);
|
||||
DataOutputStream dos = new DataOutputStream(bais);
|
||||
dos.writeInt(value);
|
||||
data = bais.toByteArray();
|
||||
bais.close();
|
||||
dos.close();
|
||||
return data;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] longToByteArray(long value) {
|
||||
try {
|
||||
byte[] data = null;
|
||||
ByteArrayOutputStream bais = new ByteArrayOutputStream(8);
|
||||
DataOutputStream dos = new DataOutputStream(bais);
|
||||
dos.writeLong(value);
|
||||
data = bais.toByteArray();
|
||||
bais.close();
|
||||
dos.close();
|
||||
return data;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Long readUnsingedInt(byte[] data, int offset) {
|
||||
try {
|
||||
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
|
||||
dis.skip(offset);
|
||||
Long retval = null;
|
||||
int tmp = dis.readInt();
|
||||
if (tmp < 0) {
|
||||
retval = tmp + 4294967296L;
|
||||
}
|
||||
else {
|
||||
retval = Long.valueOf(tmp);
|
||||
}
|
||||
|
||||
dis.close();
|
||||
return retval;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isNumeric(String str) {
|
||||
Pattern pattern = Pattern.compile("[0-9]*");
|
||||
Matcher isNum = pattern.matcher(str);
|
||||
if (!isNum.matches()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
1449
comm/Kernel/src/kernel/util/ObjectTools.java
Executable file
1449
comm/Kernel/src/kernel/util/ObjectTools.java
Executable file
File diff suppressed because it is too large
Load Diff
116
comm/Kernel/src/kernel/util/PageInfo.java
Executable file
116
comm/Kernel/src/kernel/util/PageInfo.java
Executable file
@@ -0,0 +1,116 @@
|
||||
package kernel.util;
|
||||
|
||||
import kernel.web.Page;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PageInfo implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private List elements = new ArrayList<>();
|
||||
private static final int DEFAULT_PAGE_SIZE = 10;
|
||||
|
||||
private int pageSize = DEFAULT_PAGE_SIZE;
|
||||
|
||||
private int pageNum = 1;
|
||||
|
||||
private int totalElements = 0;
|
||||
|
||||
public static final Page EMPTY_PAGE = new Page();
|
||||
|
||||
public PageInfo() {
|
||||
}
|
||||
|
||||
public void setPageSize(int pageSize) {
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
|
||||
public void setPageNum(int pageNum) {
|
||||
if (pageNum > 0) {
|
||||
this.pageNum = pageNum;
|
||||
}
|
||||
}
|
||||
|
||||
public PageInfo(int pageNum, int pageSize, int totalElements) {
|
||||
if (pageNum > 0) {
|
||||
this.pageNum = pageNum;
|
||||
}
|
||||
if (pageSize > 0) {
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
if (totalElements > 0)
|
||||
this.totalElements = totalElements;
|
||||
}
|
||||
|
||||
public boolean isFirstPage() {
|
||||
return getPageNum() == 1;
|
||||
}
|
||||
|
||||
public boolean isLastPage() {
|
||||
return getPageNum() >= getTotalPage();
|
||||
}
|
||||
|
||||
public boolean hasNextPage() {
|
||||
return getTotalPage() > getPageNum();
|
||||
}
|
||||
|
||||
public boolean hasPreviousPage() {
|
||||
return getPageNum() > 1;
|
||||
}
|
||||
|
||||
public int getTotalPage() {
|
||||
return this.totalElements % this.pageSize == 0 ? this.totalElements / this.pageSize
|
||||
: this.totalElements / this.pageSize + 1;
|
||||
}
|
||||
|
||||
public List getElements() {
|
||||
return this.elements;
|
||||
}
|
||||
|
||||
public void setElements(List elements) {
|
||||
this.elements = elements;
|
||||
}
|
||||
|
||||
public int getTotalElements() {
|
||||
return this.totalElements;
|
||||
}
|
||||
|
||||
public void setTotalElements(int totalElements) {
|
||||
if (totalElements > 0) {
|
||||
this.totalElements = totalElements;
|
||||
}
|
||||
if (this.pageNum > getTotalPage())
|
||||
this.pageNum = getTotalPage();
|
||||
}
|
||||
|
||||
public int getFirstElementNumber() {
|
||||
return (getPageNum() - 1) * getPageSize();
|
||||
}
|
||||
|
||||
public int getLastElementNumber() {
|
||||
int fullPage = getFirstElementNumber() + getPageSize() - 1;
|
||||
return getTotalElements() < fullPage ? getTotalElements() : fullPage;
|
||||
}
|
||||
|
||||
public int getNextPageNumber() {
|
||||
return getPageNum() + 1;
|
||||
}
|
||||
|
||||
public int getPreviousPageNumber() {
|
||||
return getPageNum() - 1;
|
||||
}
|
||||
|
||||
public int getPageSize() {
|
||||
return this.pageSize;
|
||||
}
|
||||
|
||||
public int getPageNum() {
|
||||
return this.pageNum;
|
||||
}
|
||||
|
||||
public int getFirstPage() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
268
comm/Kernel/src/kernel/util/PoiUtil.java
Executable file
268
comm/Kernel/src/kernel/util/PoiUtil.java
Executable file
@@ -0,0 +1,268 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.List;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.poi.hssf.usermodel.HSSFCell;
|
||||
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
|
||||
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
|
||||
//import org.apache.poi.hssf.usermodel.HSSFDateUtil;
|
||||
import org.apache.poi.hssf.usermodel.HSSFFont;
|
||||
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
|
||||
import org.apache.poi.hssf.usermodel.HSSFRow;
|
||||
import org.apache.poi.hssf.usermodel.HSSFSheet;
|
||||
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.Drawing;
|
||||
import org.apache.poi.ss.usermodel.Font;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
|
||||
import util.Strings;
|
||||
|
||||
|
||||
/**
|
||||
30.
|
||||
31. * 生成excel的通用模版
|
||||
33. *
|
||||
35. * @param response 响应,设置生成的文件类型,文件头编码方式和文件名,以及输出
|
||||
37. * @param list 表的内容,List类型,里面的每个节点是String[]型
|
||||
39. * @param firstLine 标题字符串数组 String[]
|
||||
41. * @param sheetName 表名
|
||||
43. * @param fileName 文件名
|
||||
45. */
|
||||
public class PoiUtil {
|
||||
|
||||
public static String getCell(Cell cell) {
|
||||
// DecimalFormat df = new DecimalFormat("#.##");
|
||||
// if (cell == null)
|
||||
// return "";
|
||||
// switch (cell.getCellType()) {
|
||||
// case HSSFCell.CELL_TYPE_NUMERIC:
|
||||
// if(HSSFDateUtil.isCellDateFormatted(cell)){
|
||||
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
// return Strings.emptyIfNull(sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString());
|
||||
// }
|
||||
// return Strings.emptyIfNull(df.format(cell.getNumericCellValue()));
|
||||
// case HSSFCell.CELL_TYPE_STRING:
|
||||
// return Strings.emptyIfNull(cell.getStringCellValue());
|
||||
// case HSSFCell.CELL_TYPE_FORMULA:
|
||||
// return Strings.emptyIfNull(cell.getCellFormula());
|
||||
// case HSSFCell.CELL_TYPE_BLANK:
|
||||
// return "";
|
||||
// case HSSFCell.CELL_TYPE_BOOLEAN:
|
||||
// return Strings.emptyIfNull(cell.getBooleanCellValue() + "");
|
||||
// case HSSFCell.CELL_TYPE_ERROR:
|
||||
// return Strings.emptyIfNull(cell.getErrorCellValue() + "");
|
||||
// }
|
||||
return "";
|
||||
}
|
||||
|
||||
|
||||
public static String getValue(HSSFCell hssfCell) {
|
||||
// if (hssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
|
||||
// // 返回布尔类型的值
|
||||
// return String.valueOf(hssfCell.getBooleanCellValue());
|
||||
// } else if (hssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
|
||||
// // 返回数值类型的值
|
||||
// return String.valueOf(hssfCell.getNumericCellValue());
|
||||
// } else {
|
||||
// // 返回字符串类型的值
|
||||
// return String.valueOf(hssfCell.getStringCellValue());
|
||||
// }
|
||||
return "";
|
||||
}
|
||||
//填充内容
|
||||
public static int createCell(List list,Drawing patriarch,Workbook wb, Sheet sheet,Row row,Cell cell,CellStyle style, Integer i) throws IOException {
|
||||
//生成所有行的单元格内容,如果测试list设为null即可,或者将这一段代码注释掉
|
||||
Object[] array1 = null;
|
||||
if (null == list || list.size() == 0) {
|
||||
// do nothing
|
||||
} else {
|
||||
for (int k = 0; k < list.size(); k++) {
|
||||
row = sheet.createRow(++i);
|
||||
row.setHeightInPoints(33);
|
||||
array1 = (Object[]) list.get(k);
|
||||
if (null != array1 && array1.length != 0) {
|
||||
for (int f = 0; f < array1.length; f++) {
|
||||
if (array1[f] instanceof BufferedImage){
|
||||
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
|
||||
ImageIO.write((BufferedImage)array1[f],"jpg",byteArrayOut);
|
||||
HSSFClientAnchor anchor = new HSSFClientAnchor(0,0,1020,255,(short)f,k+1,(short)f,k+1);//
|
||||
// anchor.setAnchorType(2);
|
||||
patriarch.createPicture(anchor , wb.addPicture(byteArrayOut.toByteArray(),Workbook.PICTURE_TYPE_JPEG));
|
||||
}else{
|
||||
cell = row.createCell((short) f);
|
||||
cell.setCellStyle(style);
|
||||
// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
|
||||
cell.setCellValue(String.valueOf(array1[f]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
//填充内容
|
||||
public static int createCommonSearchCell(List list,Workbook wb, Sheet sheet,Row row,Cell cell,CellStyle style, Integer i) throws IOException {
|
||||
//生成所有行的单元格内容,如果测试list设为null即可,或者将这一段代码注释掉
|
||||
Object[] array1 = null;
|
||||
if (null == list || list.size() == 0) {
|
||||
// do nothing
|
||||
} else {
|
||||
for (int k = 0; k < list.size(); k++) {
|
||||
row = sheet.createRow(++i);
|
||||
row.setHeightInPoints(33);
|
||||
array1 = (Object[]) list.get(k);
|
||||
if (null != array1 && array1.length != 0) {
|
||||
for (int f = 0; f < array1.length; f++) {
|
||||
cell = row.createCell((short) f);
|
||||
// cell.setCellStyle(style);
|
||||
// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
|
||||
cell.setCellValue(String.valueOf(array1[f]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
//生成表头
|
||||
public static void createHead(HttpServletResponse response,String[] firstLine,Workbook wb, Sheet sheet ,CellStyle style,Row row,Cell cell, Integer i, String sheetName, String fileName) {
|
||||
try {
|
||||
response.setContentType("application/vnd.ms-excel");//设置生成的文件类型
|
||||
response.setHeader("Content-Disposition", "filename="
|
||||
+ new String(fileName.getBytes("gb2312"), "iso8859-1"));//设置文件头编码方式和文件名
|
||||
// HSSFWorkbook wb = new HSSFWorkbook();//excel文件,一个excel文件包含多个表
|
||||
//HSSFSheet sheet = wb.createSheet();//表,一个表包含多个行
|
||||
// wb.setSheetName(0, sheetName, HSSFWorkbook.ENCODING_UTF_16);// 设置sheet中文编码;
|
||||
//设置字体等样式
|
||||
Font font = wb.createFont();
|
||||
font.setFontHeightInPoints((short) 10);
|
||||
font.setFontName("Courier New");
|
||||
// HSSFCellStyle style = wb.createCellStyle();
|
||||
style.setFont(font);
|
||||
style.setWrapText(true);
|
||||
// style.setAlignment(CellStyle.ALIGN_LEFT);
|
||||
// style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
|
||||
//声明一个画图的顶级管理器
|
||||
// HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
|
||||
// HSSFRow row;//行,一行包括多个单元格
|
||||
// HSSFCell cell;//单元格
|
||||
row = sheet.createRow(i);//由HSSFSheet生成行
|
||||
row.setHeightInPoints(30);
|
||||
//生成首行
|
||||
for (short j = 0; j < firstLine.length; j++) {
|
||||
cell = row.createCell(j);//由行生成单元格
|
||||
cell.setCellStyle(style);
|
||||
// cell.setEncoding(HSSFCell.ENCODING_UTF_16);// 设置cell中文编码;
|
||||
cell.setCellValue(firstLine[j]);
|
||||
sheet.setColumnWidth(j, (short) (6000));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
// return;
|
||||
}
|
||||
|
||||
public static void out(Workbook wb,HttpServletResponse response){
|
||||
//输出
|
||||
try{
|
||||
OutputStream out = response.getOutputStream();
|
||||
wb.write(out);
|
||||
//注意看以下几句的使用
|
||||
out.flush();
|
||||
out.close();
|
||||
} catch (Exception ex) {
|
||||
// ex.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
public static void excel(HttpServletResponse response, List list,
|
||||
String[] firstLine, String sheetName, String fileName) {
|
||||
Object[] array1 = null;
|
||||
try {
|
||||
short i = 0;// row行标
|
||||
response.setContentType("application/vnd.ms-excel");//设置生成的文件类型
|
||||
response.setHeader("Content-Disposition", "filename="
|
||||
+ new String(fileName.getBytes("gb2312"), "iso8859-1"));//设置文件头编码方式和文件名
|
||||
HSSFWorkbook wb = new HSSFWorkbook();//excel文件,一个excel文件包含多个表
|
||||
HSSFSheet sheet = wb.createSheet();//表,一个表包含多个行
|
||||
// wb.setSheetName(0, sheetName, HSSFWorkbook.ENCODING_UTF_16);// 设置sheet中文编码;
|
||||
//设置字体等样式
|
||||
HSSFFont font = wb.createFont();
|
||||
font.setFontHeightInPoints((short) 10);
|
||||
font.setFontName("Courier New");
|
||||
HSSFCellStyle style = wb.createCellStyle();
|
||||
style.setFont(font);
|
||||
style.setWrapText(true);
|
||||
// style.setAlignment(CellStyle.ALIGN_LEFT);
|
||||
// style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
|
||||
//声明一个画图的顶级管理器
|
||||
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
|
||||
HSSFRow row;//行,一行包括多个单元格
|
||||
HSSFCell cell;//单元格
|
||||
//生成首行
|
||||
if(firstLine!=null&&firstLine.length>0){
|
||||
row = sheet.createRow(i);//由HSSFSheet生成行
|
||||
row.setHeightInPoints(25);
|
||||
for (short j = 0; j < firstLine.length; j++) {
|
||||
cell = row.createCell(j);//由行生成单元格
|
||||
cell.setCellStyle(style);
|
||||
// cell.setEncoding(HSSFCell.ENCODING_UTF_16);// 设置cell中文编码;
|
||||
cell.setCellValue(firstLine[j]);
|
||||
sheet.setColumnWidth(j, (short) (6000));
|
||||
}
|
||||
}
|
||||
//生成所有行的单元格内容,如果测试list设为null即可,或者将这一段代码注释掉
|
||||
if (null == list || list.size() == 0) {
|
||||
// do nothing
|
||||
} else {
|
||||
for (int k = 0; k < list.size(); k++) {
|
||||
row = sheet.createRow(((firstLine==null||firstLine.length==0)&&k==0)?0:++i);
|
||||
row.setHeightInPoints(33);
|
||||
array1 = (Object[]) list.get(k);
|
||||
if (null != array1 && array1.length != 0) {
|
||||
for (int f = 0; f < array1.length; f++) {
|
||||
if (array1[f] instanceof BufferedImage){
|
||||
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
|
||||
ImageIO.write((BufferedImage)array1[f],"jpg",byteArrayOut);
|
||||
HSSFClientAnchor anchor = new HSSFClientAnchor(0,0,1020,255,(short)f,k+1,(short)f,k+1);//
|
||||
// anchor.setAnchorType(2);
|
||||
patriarch.createPicture(anchor , wb.addPicture(byteArrayOut.toByteArray(),Workbook.PICTURE_TYPE_JPEG));
|
||||
}else{
|
||||
cell = row.createCell((short) f);
|
||||
cell.setCellStyle(style);
|
||||
// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
|
||||
cell.setCellValue(String.valueOf(array1[f]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for(int j=0;j<firstLine.length;j++){
|
||||
sheet.autoSizeColumn((short)j);
|
||||
}
|
||||
//输出
|
||||
OutputStream out = response.getOutputStream();
|
||||
wb.write(out);
|
||||
out.close();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
27
comm/Kernel/src/kernel/util/PropertiesLoaderUtils.java
Executable file
27
comm/Kernel/src/kernel/util/PropertiesLoaderUtils.java
Executable file
@@ -0,0 +1,27 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
|
||||
public class PropertiesLoaderUtils extends org.springframework.core.io.support.PropertiesLoaderUtils {
|
||||
|
||||
public static void merge(Properties target, Properties source) {
|
||||
target.putAll(source);
|
||||
}
|
||||
|
||||
public static Properties loadProperties(String path){
|
||||
Properties props = new Properties();
|
||||
Resource resource = new ClassPathResource(path);
|
||||
try {
|
||||
PropertiesLoaderUtils.fillProperties(props, resource);
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
return props;
|
||||
}
|
||||
}
|
||||
133
comm/Kernel/src/kernel/util/PropertiesUtil.java
Executable file
133
comm/Kernel/src/kernel/util/PropertiesUtil.java
Executable file
@@ -0,0 +1,133 @@
|
||||
package kernel.util;
|
||||
|
||||
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
/**
|
||||
* 读取Properties综合类,默认绑定到classpath下的config.properties文件。
|
||||
*/
|
||||
public class PropertiesUtil {
|
||||
private static Log log = LogFactory.getLog(PropertiesUtil.class);
|
||||
private static String CONFIG_FILENAME = "config/system.properties";
|
||||
private static Properties prop = null;
|
||||
|
||||
public PropertiesUtil() {
|
||||
if (prop == null) {
|
||||
loadProperties();
|
||||
}
|
||||
};
|
||||
|
||||
private synchronized static void loadProperties() {
|
||||
byte buff[]=null;
|
||||
try {
|
||||
//Open the props file
|
||||
InputStream is=PropertiesUtil.class.getResourceAsStream("/" + CONFIG_FILENAME);
|
||||
prop = new Properties();
|
||||
//Read in the stored properties
|
||||
prop.load(is);
|
||||
}
|
||||
catch (Exception e) {
|
||||
System.err.println("读取配置文件失败!!!");
|
||||
prop = null;
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到属性值
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static String getProperty(String key) {
|
||||
if (prop == null) {
|
||||
loadProperties();
|
||||
}
|
||||
|
||||
String value = prop.getProperty(key);
|
||||
if(value ==null){
|
||||
return null;
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到内容包含汉字的属性值
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static String getGBKProperty(String key) {
|
||||
String value = getProperty(key);
|
||||
try {
|
||||
value = new String(value.getBytes("ISO8859-1"),"GBK");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
}
|
||||
|
||||
if(value ==null){
|
||||
return null;
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到属性值,
|
||||
* @param key
|
||||
* @param defaultValue
|
||||
* @return
|
||||
*/
|
||||
public static String getProperty(String key, String defaultValue) {
|
||||
if (prop == null) {
|
||||
loadProperties();
|
||||
}
|
||||
|
||||
String value = prop.getProperty(key, defaultValue);
|
||||
if(value ==null){
|
||||
return null;
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到内容包含汉字的属性值,如果不存在则使用默认值
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static String getGBKProperty(String key, String defaultValue) {
|
||||
try {
|
||||
defaultValue = new String(defaultValue.getBytes("GBK"), "ISO8859-1");
|
||||
String value = getProperty(key, defaultValue);
|
||||
value = new String(value.getBytes("ISO8859-1"), "GBK");
|
||||
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return value.trim();
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getUTFProperty(String key, String defaultValue) {
|
||||
try {
|
||||
defaultValue = new String(defaultValue.getBytes("UTF-8"),
|
||||
"ISO8859-1");
|
||||
String value = getProperty(key, defaultValue);
|
||||
value = new String(value.getBytes("ISO8859-1"), "UTF-8");
|
||||
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
return value.trim();
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(PropertiesUtil.getProperty("admin_url"));
|
||||
}
|
||||
}
|
||||
50
comm/Kernel/src/kernel/util/RandomNumberUtil.java
Executable file
50
comm/Kernel/src/kernel/util/RandomNumberUtil.java
Executable file
@@ -0,0 +1,50 @@
|
||||
package kernel.util;
|
||||
import org.apache.commons.lang.RandomStringUtils;
|
||||
import org.apache.commons.lang.math.RandomUtils;
|
||||
public class RandomNumberUtil {
|
||||
private static final int[] prefix = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
|
||||
|
||||
/**
|
||||
* 随机产生最大为18位的long型数据(long型数据的最大值是9223372036854775807,共有19位)
|
||||
*
|
||||
* @param digit
|
||||
* 用户指定随机数据的位数
|
||||
*/
|
||||
public static long randomLong(int digit) {
|
||||
if (digit >= 19 || digit <= 0)
|
||||
throw new IllegalArgumentException("digit should between 1 and 18(1<=digit<=18)");
|
||||
String s = RandomStringUtils.randomNumeric(digit - 1);
|
||||
return Long.parseLong(getPrefix() + s);
|
||||
}
|
||||
|
||||
/**
|
||||
* 随机产生在指定位数之间的long型数据,位数包括两边的值,minDigit<=maxDigit
|
||||
*
|
||||
* @param minDigit
|
||||
* 用户指定随机数据的最小位数 minDigit>=1
|
||||
* @param maxDigit
|
||||
* 用户指定随机数据的最大位数 maxDigit<=18
|
||||
*/
|
||||
public static long randomLong(int minDigit, int maxDigit) {
|
||||
if (minDigit > maxDigit) {
|
||||
throw new IllegalArgumentException("minDigit > maxDigit");
|
||||
}
|
||||
if (minDigit <= 0 || maxDigit >= 19) {
|
||||
throw new IllegalArgumentException("minDigit <=0 || maxDigit>=19");
|
||||
}
|
||||
return randomLong(minDigit + getDigit(maxDigit - minDigit));
|
||||
}
|
||||
|
||||
private static int getDigit(int max) {
|
||||
return RandomUtils.nextInt(max + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保证第一位不是零
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private static String getPrefix() {
|
||||
return prefix[RandomUtils.nextInt(9)] + "";
|
||||
}
|
||||
}
|
||||
115
comm/Kernel/src/kernel/util/RandomUtils.java
Executable file
115
comm/Kernel/src/kernel/util/RandomUtils.java
Executable file
@@ -0,0 +1,115 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* random utils
|
||||
*/
|
||||
public class RandomUtils {
|
||||
|
||||
/**
|
||||
* character table
|
||||
*/
|
||||
private static final char[] CHAR_TABLE = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
|
||||
|
||||
/**
|
||||
* number table
|
||||
*/
|
||||
private static final char[] NUM_TABLE = "0123456789".toCharArray();
|
||||
|
||||
/**
|
||||
* number table
|
||||
*/
|
||||
private static final char[] NUM_CHAR_TABLE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
|
||||
|
||||
/**
|
||||
* genernate random string
|
||||
* @param length length
|
||||
* @return random string
|
||||
*/
|
||||
public static String randomString(int length) {
|
||||
Random random = new Random();
|
||||
StringBuilder sb = new StringBuilder(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
int pos = random.nextInt(CHAR_TABLE.length);
|
||||
sb.append(CHAR_TABLE[pos]);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static boolean isNumeric(String str){
|
||||
Pattern pattern = Pattern.compile("[0-9]*");
|
||||
return pattern.matcher(str).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* genernate random num
|
||||
* @param length length
|
||||
* @return random string
|
||||
*/
|
||||
public static String randomNum(int length) {
|
||||
Random random = new Random();
|
||||
StringBuilder sb = new StringBuilder(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
int pos = random.nextInt(NUM_TABLE.length);
|
||||
sb.append(NUM_TABLE[pos]);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* random byte
|
||||
* @return random byte
|
||||
*/
|
||||
public static byte randomByte() {
|
||||
Random random = new Random();
|
||||
return (byte) random.nextInt();
|
||||
}
|
||||
|
||||
/**
|
||||
* genernate random code
|
||||
* @param length length
|
||||
* @return random string
|
||||
*/
|
||||
public static String randomCode(int length) {
|
||||
Random random = new Random();
|
||||
StringBuilder sb = new StringBuilder(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
int pos = random.nextInt(NUM_CHAR_TABLE.length);
|
||||
sb.append(NUM_CHAR_TABLE[pos]);
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成32位唯一的UUID字符串
|
||||
* @return
|
||||
*/
|
||||
public static String uuid32() {
|
||||
return java.util.UUID.randomUUID().toString().replaceAll("-", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回min-max之间的随机数
|
||||
* @param min(包含)
|
||||
* @param max(包含)
|
||||
* @return
|
||||
*/
|
||||
public static int randomIntWithMax(int min, int max){
|
||||
if(min >= max){
|
||||
return min;
|
||||
}
|
||||
int random = (int) (Math.random()*(max-min+1)+min);
|
||||
return random;
|
||||
}
|
||||
|
||||
}
|
||||
33
comm/Kernel/src/kernel/util/RejectExecutionHandlerDelegator.java
Executable file
33
comm/Kernel/src/kernel/util/RejectExecutionHandlerDelegator.java
Executable file
@@ -0,0 +1,33 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.concurrent.RejectedExecutionHandler;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
|
||||
public class RejectExecutionHandlerDelegator implements RejectedExecutionHandler {
|
||||
|
||||
private static final Log logger = LogFactory.getLog(RejectExecutionHandlerDelegator.class);
|
||||
|
||||
private Collection<RejectedExecutionHandler> rejectExecutionHandlers = new ArrayList<RejectedExecutionHandler>();
|
||||
/* (non-Javadoc)
|
||||
* @see java.util.concurrent.RejectedExecutionHandler#rejectedExecution(java.lang.Runnable, java.util.concurrent.ThreadPoolExecutor)
|
||||
*/
|
||||
public void rejectedExecution(Runnable runner, ThreadPoolExecutor executor) {
|
||||
logger.warn("do rejected Execution with runner[" + runner + "], executor[" + executor + "]");
|
||||
for(RejectedExecutionHandler rejectExecutionHandler : rejectExecutionHandlers){
|
||||
rejectExecutionHandler.rejectedExecution(runner, executor);
|
||||
}
|
||||
}
|
||||
|
||||
public void setRejectExecutionHandlers(Collection<RejectedExecutionHandler> rejectExecutionHandlers) {
|
||||
Assert.notEmpty(rejectExecutionHandlers);
|
||||
this.rejectExecutionHandlers = rejectExecutionHandlers;
|
||||
}
|
||||
|
||||
}
|
||||
31
comm/Kernel/src/kernel/util/ServletUtil.java
Executable file
31
comm/Kernel/src/kernel/util/ServletUtil.java
Executable file
@@ -0,0 +1,31 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
public class ServletUtil {
|
||||
|
||||
|
||||
public static final String ENCODING = "UTF-8";
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 输出XML信息
|
||||
*
|
||||
* @param response
|
||||
* @param xmlStr
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void outputXML(HttpServletResponse response, String xmlStr)
|
||||
throws IOException {
|
||||
response.setContentType("text/html;charset=" + ENCODING);
|
||||
PrintWriter out = response.getWriter();
|
||||
out.println(xmlStr);
|
||||
out.close();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
614
comm/Kernel/src/kernel/util/StringUtils.java
Executable file
614
comm/Kernel/src/kernel/util/StringUtils.java
Executable file
@@ -0,0 +1,614 @@
|
||||
/**
|
||||
*
|
||||
*/
|
||||
package kernel.util;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.math.BigDecimal;
|
||||
import java.net.URLDecoder;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.util.Assert;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
public abstract class StringUtils extends org.springframework.util.StringUtils {
|
||||
|
||||
private static final Log logger = LogFactory.getLog(StringUtils.class);
|
||||
|
||||
public static boolean isNullOrEmpty(String string) {
|
||||
return string == null || string.trim().length() == 0;
|
||||
}
|
||||
|
||||
public static boolean isEmptyString(String str) {
|
||||
return isNullOrEmpty(str);
|
||||
}
|
||||
|
||||
public static boolean isNotEmpty(String str) {
|
||||
return !isNullOrEmpty(str);
|
||||
}
|
||||
|
||||
public static String getBlank(int blankNum) {
|
||||
StringBuffer blanks = new StringBuffer();
|
||||
for (int i = 0; i < blankNum; i++) {
|
||||
blanks.append(" ");
|
||||
}
|
||||
return blanks.toString();
|
||||
}
|
||||
|
||||
public static boolean containInArray(String target, String[] list) {
|
||||
for (String dest : list) {
|
||||
if (dest.equals(target)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Description:简单的字段串连接
|
||||
|
||||
*/
|
||||
public static String join(String... strs) {
|
||||
return org.apache.commons.lang3.StringUtils.join(strs);
|
||||
}
|
||||
|
||||
public static String truncateMessage(String description, int length) {
|
||||
Assert.state(length > 0);
|
||||
if (description != null && description.length() > length) {
|
||||
logger.debug("Truncating long message, original message is: " + description);
|
||||
return description.substring(0, length);
|
||||
} else {
|
||||
return description;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字符串转义为带格式的HTML
|
||||
*
|
||||
* @param tempMsg
|
||||
* @author Song Lihua
|
||||
* @return 带格式的HTML
|
||||
*/
|
||||
// public static String wrapForHtml(String tempMsg) {
|
||||
// if (isNullOrEmpty(tempMsg)) {
|
||||
// return tempMsg;
|
||||
// }
|
||||
// tempMsg = HtmlUtils.htmlEscape(tempMsg);
|
||||
// tempMsg = tempMsg.replaceAll("\r\n", "<br/>");
|
||||
// tempMsg = tempMsg.replaceAll("\n", "<br/>");
|
||||
// tempMsg = tempMsg.replaceAll("\r", "<br/>");
|
||||
// return tempMsg.replaceAll(" ", " ");
|
||||
// }
|
||||
|
||||
/**
|
||||
* 将日期转化为字符串
|
||||
*
|
||||
* @param str
|
||||
* @param pattern
|
||||
* @return
|
||||
*/
|
||||
public static String dateToStr(Date date, String pattern) {
|
||||
SimpleDateFormat formater = new SimpleDateFormat(DateUtils.NORMAL_DATE_FORMAT);
|
||||
if (pattern != null)
|
||||
formater.applyPattern(pattern);
|
||||
return formater.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分割参数
|
||||
*
|
||||
* @param paraSrc String
|
||||
* @param sepa String
|
||||
* @return Map sample : "a=b,c=d,..."
|
||||
*/
|
||||
public static Map<String, String> splitPara(String paraSrc, String sepa) {
|
||||
if (paraSrc == null || paraSrc.trim().length() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
LinkedHashMap<String, String> paraMap = new LinkedHashMap<String, String>();
|
||||
if (sepa == null || sepa.equals("")) { // 默认分割参数的分隔符为 ","
|
||||
sepa = ",";
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
String[] paras = paraSrc.split(sepa);
|
||||
for (int i = 0, j = 0; i < paras.length; i++) {
|
||||
String tmpResult[] = paras[i].split("=");
|
||||
if (tmpResult.length >= 2) { // 2 a=b
|
||||
paraMap.put(tmpResult[0].trim(), tmpResult[1]);
|
||||
} else if (tmpResult.length == 1) {
|
||||
if (paras[i].indexOf("=") >= 0) { // 1 a=
|
||||
paraMap.put(tmpResult[0].trim(), "");
|
||||
} else { // 0 a
|
||||
paraMap.put("TEXT." + j, paras[i]);
|
||||
j++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return paraMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* return String basename
|
||||
*
|
||||
* @param name String
|
||||
* @param split String
|
||||
* @return String com.xxx.ne --> ne
|
||||
*/
|
||||
public static String pathname(String name, String split) {
|
||||
if (name == null || name.equals("")) {
|
||||
return "";
|
||||
}
|
||||
if (split == null || split.equals("")) {
|
||||
split = ".";
|
||||
}
|
||||
|
||||
int index = name.lastIndexOf(split);
|
||||
if (index >= 0) {
|
||||
return name.substring(0, index);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* return String basename
|
||||
*
|
||||
* @param name String
|
||||
* @param split String
|
||||
* @return String com.xxx.ne --> ne
|
||||
*/
|
||||
public static String basename(String name, String split) {
|
||||
if (name == null || name.equals("")) {
|
||||
return "";
|
||||
}
|
||||
if (split == null || split.equals("")) {
|
||||
split = ".";
|
||||
}
|
||||
|
||||
int index = name.lastIndexOf(split);
|
||||
if (index >= 0) {
|
||||
return name.substring(index + split.length());
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换符合正则表达式的所有子字符串为新字符串
|
||||
*
|
||||
* @param src String
|
||||
* @param pattern String
|
||||
* @param to String
|
||||
* @return String
|
||||
*/
|
||||
public static String replaceAll(String src, String pattern, String to) {
|
||||
if (src == null) {
|
||||
return null;
|
||||
}
|
||||
if (pattern == null) {
|
||||
return src;
|
||||
}
|
||||
|
||||
StringBuffer sb = new StringBuffer();
|
||||
Pattern p = Pattern.compile(pattern);
|
||||
Matcher m = p.matcher(src);
|
||||
|
||||
int i = 1;
|
||||
while (m.find()) {
|
||||
// System.out.println("找到第" + i + "个匹配:" + m.group() +
|
||||
// " 位置为:" + m.start() + "-" + (m.end() - 1));
|
||||
m.appendReplacement(sb, to);
|
||||
i++;
|
||||
}
|
||||
m.appendTail(sb);
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回某字符串中所有符合正则表达式的子字符串,以字符串数组形式返回
|
||||
*
|
||||
* @param src String
|
||||
* @param pattern String
|
||||
* @return String[]
|
||||
*/
|
||||
public static String[] findAll(String src, String pattern) {
|
||||
return findAll(src, pattern, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Description:
|
||||
* </p>
|
||||
|
||||
*/
|
||||
public static String[] findAll(String src, String pattern, int flags) {
|
||||
|
||||
if (src == null) {
|
||||
return new String[0];
|
||||
}
|
||||
if (pattern == null) {
|
||||
return new String[0];
|
||||
}
|
||||
|
||||
Pattern p = Pattern.compile(pattern, flags);
|
||||
Matcher m = p.matcher(src);
|
||||
Collection<String> l = new ArrayList<String>();
|
||||
while (m.find()) {
|
||||
l.add(m.group());
|
||||
}
|
||||
|
||||
return l.toArray(new String[] {});
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否字符串匹配
|
||||
*
|
||||
* @param src String
|
||||
* @param regexp String
|
||||
* @return boolean
|
||||
*/
|
||||
public static boolean match(String src, String regexp) {
|
||||
Pattern p = Pattern.compile(regexp);
|
||||
Matcher m = p.matcher(src);
|
||||
return m.find();
|
||||
// return m.matches(); 090413 modified
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static Locale toLocale(String locale) {
|
||||
if (StringUtils.hasText(locale)) {
|
||||
String[] values = null;
|
||||
if (locale.indexOf("_") > 0) {
|
||||
values = split(locale, "_");
|
||||
} else if (locale.indexOf("-") > 0) {
|
||||
values = split(locale, "-");
|
||||
} else {
|
||||
values = new String[0];
|
||||
}
|
||||
if (values.length == 1) {
|
||||
return new Locale(values[0]);
|
||||
}
|
||||
if (values.length == 2) {
|
||||
return new Locale(values[0], values[1]);
|
||||
}
|
||||
if (values.length == 3) {
|
||||
return new Locale(values[0], values[1], values[2]);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// public static void main(String args[]) {
|
||||
// System.out.println(StringUtils.match("SMP#", "#"));// false ?
|
||||
// System.out.println(StringUtils.match("SMP#", ".*?#"));// true
|
||||
// System.out.println(StringUtils.match("\r\nff P720 login:",
|
||||
// ".*?name:|.*?ogin:"));// false
|
||||
// System.out.println(StringUtils.verifyEmail("x@.com"));
|
||||
// // ?
|
||||
// }
|
||||
|
||||
/**
|
||||
* Stringת<67><D7AA><EFBFBD><EFBFBD>UTF-8<><38><EFBFBD><EFBFBD><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD><EFBFBD>
|
||||
*
|
||||
* @param str
|
||||
* @return byte[]
|
||||
*/
|
||||
public static byte[] getUtf8Bytes(String str) {
|
||||
try {
|
||||
return str.getBytes("UTF-8");
|
||||
} catch (UnsupportedEncodingException uee) {
|
||||
return str.getBytes();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* UTF-8<><38>ʽ<EFBFBD>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD><EFBFBD>ת<EFBFBD><D7AA><EFBFBD><EFBFBD>String
|
||||
*
|
||||
* @param utf8
|
||||
* @return String
|
||||
*/
|
||||
public static String getStringFromUtf8(byte[] utf8) {
|
||||
try {
|
||||
return new String(utf8, "UTF-8");
|
||||
} catch (UnsupportedEncodingException uee) {
|
||||
return new String(utf8);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><>list<73>е<EFBFBD>ֵʹ<D6B5>ö<EFBFBD><C3B6><EFBFBD>ƴ<EFBFBD><C6B4><EFBFBD><EFBFBD>4<EFBFBD><34><EFBFBD><EFBFBD>
|
||||
*
|
||||
* @param list
|
||||
* @return String
|
||||
*/
|
||||
public static String toString(List<?> list) {
|
||||
if (list == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuffer stringBuffer = new StringBuffer(256);
|
||||
for (Iterator<?> iter = list.iterator(); iter.hasNext();) {
|
||||
stringBuffer.append((String) iter.next());
|
||||
if (iter.hasNext()) {
|
||||
stringBuffer.append(",");
|
||||
}
|
||||
}
|
||||
return stringBuffer.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>е<EFBFBD>ֵʹ<D6B5>ö<EFBFBD><C3B6><EFBFBD>ƴ<EFBFBD><C6B4><EFBFBD><EFBFBD>4<EFBFBD><34><EFBFBD><EFBFBD>
|
||||
*
|
||||
* @param list
|
||||
* @return String
|
||||
*/
|
||||
public static String toString(Object[] objs) {
|
||||
if (objs == null || objs.length == 0) {
|
||||
return "";
|
||||
}
|
||||
return toString(Arrays.asList(objs));
|
||||
}
|
||||
|
||||
/**
|
||||
* by yangxw in 2008.03.06 <20>ַ<EFBFBD><D6B7>滻<EFBFBD><E6BBBB><EFBFBD><EFBFBD>
|
||||
*
|
||||
* @param con <20><>Ҫ<EFBFBD><D2AA><EFBFBD><EFBFBD><EFBFBD>滻<EFBFBD><E6BBBB>ԭ4<D4AD>ַ<EFBFBD>
|
||||
* @param tag Ҫ<><D2AA><EFBFBD>滻<EFBFBD><E6BBBB><EFBFBD>ַ<EFBFBD>
|
||||
* @param rep <20>滻<EFBFBD>ɵ<EFBFBD><C9B5>ַ<EFBFBD>
|
||||
* @return <20>滻<EFBFBD><E6BBBB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>µĵ<C2B5><C4B5>ַ<EFBFBD>
|
||||
*/
|
||||
@Deprecated
|
||||
public static String str_replace(String con, String tag, String rep) {
|
||||
int j = 0;
|
||||
int i = 0;
|
||||
String RETU = "";
|
||||
String temp = con;
|
||||
int tagc = tag.length();
|
||||
while (i < con.length()) {
|
||||
if (con.substring(i).startsWith(tag)) {
|
||||
temp = con.substring(j, i) + rep;
|
||||
RETU += temp;
|
||||
i += tagc;
|
||||
j = i;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
RETU += con.substring(j);
|
||||
return RETU;
|
||||
}
|
||||
|
||||
/**
|
||||
* by mengrj 2008-08-01 <20>ַ<EFBFBD>a<EFBFBD><61><EFBFBD>Ƿ<EFBFBD><C7B7><EFBFBD><EFBFBD><EFBFBD>ַ<EFBFBD>b<EFBFBD><62><EFBFBD>е<EFBFBD><D0B5>ַ<EFBFBD>
|
||||
*
|
||||
* @param a
|
||||
* @param b
|
||||
* @return
|
||||
*/
|
||||
public static boolean isContainChar(String a, String b) {
|
||||
if (a == null || b == null)
|
||||
return false;
|
||||
char[] bset = b.toCharArray();
|
||||
for (int i = 0; i < bset.length; i++) {
|
||||
for (int j = 0; j < a.length(); j++) {
|
||||
if (bset[i] == a.charAt(j))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* ȥ<><C8A5>HTML<4D><4C>ǣ<EFBFBD><C7A3><EFBFBD><EFBFBD>ش<EFBFBD><D8B4>ı<EFBFBD>
|
||||
*
|
||||
* @author chenhh
|
||||
* @param htmlStr Ҫת<D2AA><D7AA>HTML<4D>ı<EFBFBD>
|
||||
* @return String ת<><D7AA><EFBFBD><EFBFBD>Ĵ<EFBFBD><C4B4>ı<EFBFBD>
|
||||
*/
|
||||
@Deprecated
|
||||
public static String htmlToStr(String htmlStr) {
|
||||
String regEx = "<\\s*img\\s+([^>]+)\\s*>";
|
||||
Pattern p = Pattern.compile(regEx);
|
||||
Matcher m = p.matcher(htmlStr);
|
||||
return m.replaceAll("").replace(" ", "");
|
||||
}
|
||||
|
||||
public static String toUpperCase(String value) {
|
||||
return value == null ? null : value.toUpperCase();
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static String upperCase(String s) {
|
||||
return toUpperCase(s);
|
||||
}
|
||||
|
||||
public static boolean isSameByTrim(String str1, String str2) {
|
||||
if (str1 == null || str1 == null) {
|
||||
return false;
|
||||
}
|
||||
return str1.trim().equals(str2.trim());
|
||||
}
|
||||
|
||||
// add by zhoubengang <20><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD><EFBFBD>ַ<EFBFBD>
|
||||
@Deprecated
|
||||
public static String substring(String str, int toCount, String more) {
|
||||
int reInt = 0;
|
||||
String reStr = "";
|
||||
if (str == null)
|
||||
return "";
|
||||
char[] tempChar = str.toCharArray();
|
||||
for (int kk = 0; (kk < tempChar.length && toCount > reInt); kk++) {
|
||||
String s1 = String.valueOf(tempChar[kk]);
|
||||
byte[] b = s1.getBytes();
|
||||
reInt += b.length;
|
||||
reStr += tempChar[kk];
|
||||
}
|
||||
if (toCount == reInt || (toCount == reInt - 1))
|
||||
reStr += more;
|
||||
return reStr;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static String mbToTGM(BigDecimal mb) {
|
||||
return NumberUtils.mbToTGM(mb);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static boolean isNumeric(String str) {
|
||||
return NumberUtils.isNumeric(str);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static String bytesToHexString(byte[] ba) {
|
||||
return ByteUtils.bytes2hex(ba);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static String bytesToHexString(byte[] ba, String prefix) {
|
||||
if ((ba == null) || (prefix == null)) {
|
||||
throw new NullPointerException();
|
||||
}
|
||||
|
||||
StringBuffer sb = new StringBuffer();
|
||||
sb.append(prefix);
|
||||
sb.append(ByteUtils.bytes2hex(ba));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static String bytesToHexStringForDebug(byte[] ba, String prefix) {
|
||||
return bytesToHexString(ba, prefix);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static byte[] hexStringToBytes(String hexStr) {
|
||||
return ByteUtils.hex2bytes(hexStr);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static byte[] hexStringToBytes(String hexStr, String prefix) {
|
||||
if ((hexStr == null) || (prefix == null)) {
|
||||
throw new NullPointerException();
|
||||
}
|
||||
String myHexStr = hexStr.trim();
|
||||
if (myHexStr.startsWith(prefix)) {
|
||||
myHexStr = myHexStr.substring(prefix.length());
|
||||
}
|
||||
|
||||
return ByteUtils.hex2bytes(myHexStr);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static byte[] intToByte4(int i) {
|
||||
return ByteUtils.int2bytes(i);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static byte[] shortToByte2(short i) {
|
||||
return ByteUtils.short2bytes(i);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static int byte4ToInt(byte[] b) {
|
||||
return ByteUtils.bytes2int(b);
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public static short byte2ToShort(byte[] b) {
|
||||
return (short) ByteUtils.byte2short(b);
|
||||
}
|
||||
|
||||
public static String emptyIfNull(String str) {
|
||||
if (isNullOrEmpty(str)) {
|
||||
return "";
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为整数
|
||||
* @param str 传入的字符串
|
||||
* @return 是整数返回true,否则返回false
|
||||
*/
|
||||
public static boolean isInteger(String str) {
|
||||
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
|
||||
return pattern.matcher(str).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为浮点数,包括double和float
|
||||
* @param str 传入的字符串
|
||||
* @return 是浮点数返回true,否则返回false
|
||||
*/
|
||||
public static boolean isDouble(String str) {
|
||||
Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
|
||||
return pattern.matcher(str).matches();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为日期格式
|
||||
* @param str 传入的字符串
|
||||
* @return 是日期格式返回true,否则返回false
|
||||
*/
|
||||
public static boolean isValidDate(String str) {
|
||||
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
try {
|
||||
// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
|
||||
format.setLenient(false);
|
||||
format.parse(str);
|
||||
return true;
|
||||
} catch (ParseException e) {
|
||||
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
|
||||
//e.printStackTrace();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对参数进行解码,并对特殊符号进行处理
|
||||
* @param outBuffer
|
||||
* @return
|
||||
*/
|
||||
public static String replacer(StringBuffer outBuffer) {
|
||||
String data = outBuffer.toString();
|
||||
try {
|
||||
data = data.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
|
||||
data = data.replaceAll("\\+", "%2B");
|
||||
data = URLDecoder.decode(data, "utf-8");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
//随机返回字符串数组中的字符串
|
||||
public static String RandomStr(String[] strs){
|
||||
int random_index = (int) (Math.random()*strs.length);
|
||||
return strs[random_index];
|
||||
}
|
||||
}
|
||||
22
comm/Kernel/src/kernel/util/ThreadUtils.java
Executable file
22
comm/Kernel/src/kernel/util/ThreadUtils.java
Executable file
@@ -0,0 +1,22 @@
|
||||
package kernel.util;
|
||||
|
||||
public class ThreadUtils {
|
||||
private static ThreadLocal<?> localVar;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T getThreadLocal() {
|
||||
if (localVar == null) {
|
||||
localVar = new ThreadLocal<T>();
|
||||
}
|
||||
return (T) localVar;
|
||||
}
|
||||
|
||||
public static void sleep(long millis) {
|
||||
try {
|
||||
Thread.sleep(millis);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
207
comm/Kernel/src/kernel/util/TimeWindow.java
Executable file
207
comm/Kernel/src/kernel/util/TimeWindow.java
Executable file
@@ -0,0 +1,207 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public class TimeWindow implements Runnable {
|
||||
private static Log logger = LogFactory.getLog(TimeWindow.class.getName());
|
||||
|
||||
private TimeWindow instance = null;
|
||||
|
||||
private boolean stop = false;
|
||||
|
||||
protected int timeSize = 600; // 600s
|
||||
|
||||
protected HashMap[] cache = null;
|
||||
|
||||
protected byte[] cacheLock = new byte[1];
|
||||
|
||||
private String name = "TimeWindow";
|
||||
|
||||
private void init() {
|
||||
cache = new HashMap[timeSize];
|
||||
|
||||
for (int i = 0; i < cache.length; i++) {
|
||||
cache[i] = new HashMap();
|
||||
}
|
||||
}
|
||||
|
||||
public void start() {
|
||||
if (instance == null) {
|
||||
instance = this;
|
||||
this.init();
|
||||
if (name == null || name.trim().length() == 0)
|
||||
name = "TimeWindow";
|
||||
new Thread(this, name).start();
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
if (instance != null) {
|
||||
instance = null;
|
||||
cache = null;
|
||||
this.setStop(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void run() {
|
||||
while (!stop) {
|
||||
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
}
|
||||
|
||||
synchronized (cacheLock) { // 030316 cacheLock
|
||||
if (cache != null) {
|
||||
for (int i = 0; i < timeSize - 1; i++) {
|
||||
cache[i] = cache[i + 1];
|
||||
}
|
||||
|
||||
HashMap m = new HashMap();
|
||||
cache[timeSize - 1] = m;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.warn("Time window stop.");
|
||||
}
|
||||
|
||||
public int find(Object key) {
|
||||
synchronized (cacheLock) {
|
||||
for (int i = 0; cache != null && i < timeSize; i++) {
|
||||
HashMap m = (HashMap) cache[i];
|
||||
if (m.containsKey(key))
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
public Object findObject(Object key) {
|
||||
synchronized (cacheLock) {
|
||||
for (int i = 0; cache != null && i < timeSize; i++) {
|
||||
HashMap m = (HashMap) cache[i];
|
||||
if (m.containsKey(key)) {
|
||||
Object object = m.get(key);
|
||||
return object;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Map getObjectAll() {
|
||||
HashMap map = new HashMap();
|
||||
synchronized (cacheLock) {
|
||||
for (int i = 0; cache != null && i < timeSize; i++) {
|
||||
HashMap m = (HashMap) cache[i];
|
||||
map.putAll(m);
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
public boolean add(Object key, Object o) {
|
||||
this.remove(key);
|
||||
return add(key, o, new Date());
|
||||
}
|
||||
|
||||
public void remove(Object key) {
|
||||
synchronized (cacheLock) {
|
||||
for (int i = 0; cache != null && i < timeSize; i++) {
|
||||
HashMap m = (HashMap) cache[i];
|
||||
if (m.containsKey(key)) {
|
||||
m.remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void remove(Object key, int index) {
|
||||
synchronized (cacheLock) {
|
||||
if (cache != null)
|
||||
cache[index].remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean remove(Object key, Date d) {
|
||||
|
||||
if (d == null)
|
||||
d = new Date();
|
||||
|
||||
int index = (int) ((d.getTime() / 1000) % timeSize);
|
||||
|
||||
synchronized (cacheLock) {
|
||||
if (cache != null)
|
||||
cache[index].remove(key);
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
public boolean add(Object key, Object o, Date d) {
|
||||
if (d == null)
|
||||
d = new Date();
|
||||
// 随机
|
||||
// int index = (int) ((d.getTime() / 1000) % timeSize);
|
||||
|
||||
int index = timeSize - 1;
|
||||
if(d.before(new Date())) {//d<当前时间
|
||||
index = index - (int) ((new Date().getTime()-d.getTime() )/ 1000);
|
||||
if(index<=0) return false;
|
||||
}
|
||||
synchronized (cacheLock) {
|
||||
if (cache != null)
|
||||
cache[index].put(key, o);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isStop() {
|
||||
return stop;
|
||||
}
|
||||
|
||||
public void setStop(boolean stop) {
|
||||
this.stop = stop;
|
||||
}
|
||||
|
||||
public int getTimeSize() {
|
||||
return timeSize;
|
||||
}
|
||||
|
||||
public void setTimeSize(int timeSize) {
|
||||
this.timeSize = timeSize;
|
||||
}
|
||||
|
||||
public int size() {
|
||||
int size = 0;
|
||||
|
||||
synchronized (cacheLock) {
|
||||
for (int i = 0; cache != null && i < timeSize; i++) {
|
||||
HashMap m = cache[i];
|
||||
if (m != null)
|
||||
size += m.size();
|
||||
}
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
79
comm/Kernel/src/kernel/util/Tools.java
Executable file
79
comm/Kernel/src/kernel/util/Tools.java
Executable file
@@ -0,0 +1,79 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
|
||||
public class Tools {
|
||||
|
||||
/**
|
||||
* 验证手机号码
|
||||
* @param phone true 是对的,false 是错误
|
||||
* @return
|
||||
*/
|
||||
public static boolean isPhone(String phone){
|
||||
|
||||
Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])||(17[0-9])||(18[0-9]))\\d{8}$");
|
||||
|
||||
Matcher m = p.matcher(phone);
|
||||
|
||||
return m.matches();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 验证邮箱地址
|
||||
* @param phone true 是对的,false 是错误
|
||||
* @return
|
||||
*/
|
||||
public static boolean isEmail(String email){
|
||||
|
||||
Pattern pattern = Pattern.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
|
||||
|
||||
Matcher matcher = pattern.matcher(email);
|
||||
|
||||
return matcher.matches();
|
||||
}
|
||||
|
||||
|
||||
//保留两位小数点
|
||||
public static double roundHalfUp(double f){
|
||||
|
||||
BigDecimal b = new BigDecimal(f);
|
||||
return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 美元转人民币
|
||||
* @param dollar
|
||||
* @return
|
||||
*/
|
||||
public static Double DollarToRMB(Double dollar){
|
||||
|
||||
// return roundHalfUp(dollar* Constants.RMB_DOLLAR_CONVERSION_RATE);
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
public static boolean isEmpty(String string) {
|
||||
if("null".equals(string))return true;
|
||||
return string == null || string.trim().length() == 0;
|
||||
}
|
||||
/**
|
||||
* 用来判断是否为数字
|
||||
* @param str String
|
||||
* @return true 匹配,false 不匹配
|
||||
*/
|
||||
public static boolean verifeNum(String str){
|
||||
try{
|
||||
Double.valueOf(str);
|
||||
}catch(NumberFormatException nb){
|
||||
return false;
|
||||
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
71
comm/Kernel/src/kernel/util/UUIDGenerator.java
Executable file
71
comm/Kernel/src/kernel/util/UUIDGenerator.java
Executable file
@@ -0,0 +1,71 @@
|
||||
package kernel.util;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* UUID生成器,负责生成单个/多个UUID序号<br/>
|
||||
|
||||
* */
|
||||
|
||||
public class UUIDGenerator {
|
||||
/**
|
||||
* 获得一个UUID
|
||||
* @return String
|
||||
*/
|
||||
public static String getUUID(){
|
||||
String s = UUID.randomUUID().toString();
|
||||
//去掉"-"符号
|
||||
return s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得指定数目的UUID
|
||||
* @param number int 需要获得的UUID数量
|
||||
* @return String[] UUID数组
|
||||
*/
|
||||
public static String[] getUUID(int number){
|
||||
if(number < 1){
|
||||
return null;
|
||||
}
|
||||
|
||||
String[] ss = new String[number];
|
||||
|
||||
for(int i=0;i<number;i++){
|
||||
ss[i] = getUUID();
|
||||
}
|
||||
|
||||
return ss;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
System.out.println("url."+getUUID()+"=");
|
||||
}
|
||||
}
|
||||
454
comm/Kernel/src/kernel/web/BaseAction.java
Executable file
454
comm/Kernel/src/kernel/web/BaseAction.java
Executable file
@@ -0,0 +1,454 @@
|
||||
package kernel.web;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import kernel.concurrent.ConcurrentQequestHandleStrategy;
|
||||
import kernel.exception.BusinessException;
|
||||
import kernel.util.Arith;
|
||||
import kernel.util.PageInfo;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.context.ContextLoader;
|
||||
import org.springframework.web.context.WebApplicationContext;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import kernel.util.DateUtils;
|
||||
import kernel.util.StringUtils;
|
||||
import project.hobi.HobiDataService;
|
||||
import project.invest.LanguageEnum;
|
||||
import project.party.PartyRedisKeys;
|
||||
import project.redis.RedisHandler;
|
||||
import project.user.token.TokenService;
|
||||
|
||||
public class BaseAction {
|
||||
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
public static final String SPRING_SECURITY_CONTEXT_KEY = "SPRING_SECURITY_CONTEXT";
|
||||
|
||||
protected String error;
|
||||
|
||||
protected String message;
|
||||
|
||||
protected String username_login;
|
||||
|
||||
protected String result;
|
||||
|
||||
protected String callback;
|
||||
|
||||
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
|
||||
|
||||
public ResultObject readSecurityContextFromSession(ResultObject resultObject) {
|
||||
|
||||
HttpServletRequest request = this.getRequest();
|
||||
String token = request.getParameter("token");
|
||||
|
||||
if (StringUtils.isNullOrEmpty(token)) {
|
||||
resultObject.setCode("403");
|
||||
resultObject.setMsg("请重新登录");
|
||||
return resultObject;
|
||||
}
|
||||
|
||||
TokenService tokenService = (TokenService)wac.getBean("tokenService");
|
||||
String partyId = tokenService.cacheGet(token);
|
||||
if (StringUtils.isNullOrEmpty(partyId)) {
|
||||
resultObject.setCode("403");
|
||||
resultObject.setMsg("请重新登录");
|
||||
return resultObject;
|
||||
}
|
||||
RedisHandler redisHandler = (RedisHandler) wac.getBean("redisHandler");
|
||||
String isBlack = redisHandler.getString(PartyRedisKeys.PARTY_ID_SELLER_BLACK + partyId);
|
||||
if("1".equalsIgnoreCase(isBlack)){
|
||||
resultObject.setCode("403");
|
||||
resultObject.setMsg("当前用户已经被管理员禁用");
|
||||
return resultObject;
|
||||
}
|
||||
|
||||
return resultObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从Request对象中获得客户端IP,处理了HTTP代理服务器和Nginx的反向代理截取了ip
|
||||
*
|
||||
* @param request
|
||||
* @return ip
|
||||
*/
|
||||
public String getIp(HttpServletRequest request) {
|
||||
String ip = request.getHeader("X-Forwarded-For");
|
||||
if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
|
||||
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
|
||||
int index = ip.indexOf(",");
|
||||
if (index != -1) {
|
||||
return ip.substring(0, index);
|
||||
} else {
|
||||
return ip;
|
||||
}
|
||||
}
|
||||
ip = request.getHeader("X-Real-IP");
|
||||
if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
|
||||
return ip;
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
|
||||
public String getLoginPartyId() {
|
||||
HttpServletRequest request = this.getRequest();
|
||||
String token = request.getParameter("token");
|
||||
|
||||
if (StringUtils.isNullOrEmpty(token)) {
|
||||
logger.error("token is null");
|
||||
return null;
|
||||
}
|
||||
TokenService tokenService = (TokenService)wac.getBean("tokenService");
|
||||
return tokenService.cacheGet(token);
|
||||
}
|
||||
|
||||
public PageInfo getPageInfo(HttpServletRequest request){
|
||||
int pageNum ;
|
||||
try {
|
||||
pageNum = Integer.parseInt(request.getParameter("pageNum"));
|
||||
} catch ( Exception e) {
|
||||
pageNum = 1;
|
||||
}
|
||||
if(pageNum<0 || pageNum>10000) {
|
||||
pageNum = 1;
|
||||
}
|
||||
int pageSize ;
|
||||
try {
|
||||
pageSize = Integer.parseInt(request.getParameter("pageSize"));
|
||||
} catch (Exception e) {
|
||||
pageSize = 20;
|
||||
}
|
||||
if (pageSize < 2) {
|
||||
pageSize = 50;
|
||||
}
|
||||
if (pageSize > 100) {
|
||||
pageSize = 100;
|
||||
}
|
||||
PageInfo pageInfo = new PageInfo();
|
||||
pageInfo.setPageNum(pageNum);
|
||||
pageInfo.setPageSize(pageSize);
|
||||
return pageInfo;
|
||||
}
|
||||
|
||||
public String getLanguage(HttpServletRequest request){
|
||||
String lang = request.getParameter("lang");
|
||||
if (StringUtils.isEmptyString(lang)) {
|
||||
lang = LanguageEnum.EN.getLang();
|
||||
}
|
||||
if (lang.equals("en")
|
||||
|| lang.equals("cn")
|
||||
|| lang.equals("tw")) {
|
||||
// 这三种都配置了对应的语言版本,原样返回即可
|
||||
return lang;
|
||||
}
|
||||
|
||||
// 其他语种暂未配置,默认返回英文版
|
||||
lang = "en";
|
||||
return lang;
|
||||
}
|
||||
|
||||
protected HttpServletRequest getRequest() {
|
||||
return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
|
||||
}
|
||||
|
||||
protected HttpServletResponse getResponse() {
|
||||
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
|
||||
}
|
||||
|
||||
public String getError() {
|
||||
return this.error;
|
||||
}
|
||||
|
||||
public void setError(String error) {
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return this.message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public Date toDate(String dateStr, String format) {
|
||||
Date date = null;
|
||||
if (!StringUtils.isNullOrEmpty(dateStr)) {
|
||||
try {
|
||||
date = DateUtils.toDate(dateStr, format);
|
||||
} catch (Throwable e) {
|
||||
date = null;
|
||||
System.out.println(e.getStackTrace());
|
||||
}
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
public List<Date> toRangeDate(String dateStr) {
|
||||
List<Date> list = new ArrayList<Date>();
|
||||
try {
|
||||
if (!StringUtils.isNullOrEmpty(dateStr)) {
|
||||
String begin_str = dateStr.split("-")[0].trim();
|
||||
String end_str = dateStr.split("-")[1].trim();
|
||||
|
||||
Date begin = DateUtils.toDate(begin_str, DateUtils.DF_MMddyyyy);
|
||||
Date end = DateUtils.toDate(end_str, DateUtils.DF_MMddyyyy);
|
||||
|
||||
list.add(begin);
|
||||
list.add(end);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getStackTrace());
|
||||
list = new ArrayList<Date>();
|
||||
list.add(null);
|
||||
list.add(null);
|
||||
} finally {
|
||||
if (list.size() != 2) {
|
||||
list = new ArrayList<Date>();
|
||||
list.add(null);
|
||||
list.add(null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public List<Date> toRangeSecondsDate(String dateStr) {
|
||||
List<Date> list = new ArrayList<Date>();
|
||||
try {
|
||||
if (!StringUtils.isNullOrEmpty(dateStr)) {
|
||||
String begin_str = dateStr.split("-")[0].trim();
|
||||
String end_str = dateStr.split("-")[1].trim();
|
||||
|
||||
Date begin = DateUtils.toDate(begin_str, "MM/dd/yyyy HH:mm:ss");
|
||||
Date end = DateUtils.toDate(end_str, "MM/dd/yyyy HH:mm:ss");
|
||||
list.add(begin);
|
||||
list.add(end);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getStackTrace());
|
||||
list = new ArrayList<Date>();
|
||||
list.add(null);
|
||||
list.add(null);
|
||||
} finally {
|
||||
if (list.size() != 2) {
|
||||
list = new ArrayList<Date>();
|
||||
list.add(null);
|
||||
list.add(null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public List<String> toRangeThirdsDate(String dateStr) {
|
||||
List<String> list = new ArrayList<String>();
|
||||
try {
|
||||
if (!StringUtils.isNullOrEmpty(dateStr)) {
|
||||
String begin_str = dateStr.split(" - ")[0].trim();
|
||||
String end_str = dateStr.split(" - ")[1].trim();
|
||||
|
||||
Date begin = DateUtils.toDate(begin_str, "yyyy-MM-dd HH:mm:ss");
|
||||
Date end = DateUtils.toDate(end_str, "yyyy-MM-dd HH:mm:ss");
|
||||
list.add(begin_str);
|
||||
list.add(end_str);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e.getStackTrace());
|
||||
list = new ArrayList<String>();
|
||||
list.add(null);
|
||||
list.add(null);
|
||||
} finally {
|
||||
if (list.size() != 2) {
|
||||
list = new ArrayList<String>();
|
||||
list.add(null);
|
||||
list.add(null);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public Date toDate(String dateStr) {
|
||||
Date date = null;
|
||||
if (!StringUtils.isNullOrEmpty(dateStr)) {
|
||||
try {
|
||||
date = DateUtils.toDate(dateStr, "yyyy-MM-dd");
|
||||
} catch (Throwable e) {
|
||||
System.out.println(e.getStackTrace());
|
||||
}
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
public String dateToStr(Date date, String format) {
|
||||
String dateStr = null;
|
||||
if (date != null) {
|
||||
try {
|
||||
dateStr = DateUtils.dateToStr(date, format);
|
||||
} catch (Throwable e) {
|
||||
System.out.println(e.getStackTrace());
|
||||
}
|
||||
}
|
||||
|
||||
return dateStr;
|
||||
}
|
||||
|
||||
public String dateToStr(Date date) {
|
||||
String dateStr = null;
|
||||
if (date != null) {
|
||||
try {
|
||||
dateStr = DateUtils.dateToStr(date, "yyyy-MM-dd");
|
||||
} catch (Throwable e) {
|
||||
System.out.println(e.getStackTrace());
|
||||
}
|
||||
}
|
||||
|
||||
return dateStr;
|
||||
}
|
||||
|
||||
public void addCookie(String name, String value) {
|
||||
Cookie cookie = new Cookie(name, value);
|
||||
cookie.setMaxAge(31536000);
|
||||
this.getResponse().addCookie(cookie);
|
||||
}
|
||||
|
||||
public String getCookie(String name) {
|
||||
HttpServletRequest request = this.getRequest();
|
||||
Cookie[] cookies = request.getCookies();
|
||||
for (Cookie cookie : cookies) {
|
||||
if (cookie.getName().equals(name)) {
|
||||
return cookie.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getResult() {
|
||||
return this.result;
|
||||
}
|
||||
|
||||
// public String getLocalText(String localkey, String log) {
|
||||
// String[] args = log.split(",");
|
||||
// return this.messageSource.getMessage(localkey, args, "Required", null);
|
||||
// }
|
||||
|
||||
/**
|
||||
* 从Request对象中获得客户端IP,处理了HTTP代理服务器和Nginx的反向代理截取了ip
|
||||
*
|
||||
* @return ip
|
||||
*/
|
||||
public String getIp() {
|
||||
HttpServletRequest request = this.getRequest();
|
||||
String ip = request.getHeader("X-Forwarded-For");
|
||||
if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
|
||||
// 多次反向代理后会有多个ip值,第一个ip才是真实ip
|
||||
int index = ip.indexOf(",");
|
||||
if (index != -1) {
|
||||
return ip.substring(0, index);
|
||||
} else {
|
||||
return ip;
|
||||
}
|
||||
}
|
||||
ip = request.getHeader("X-Real-IP");
|
||||
if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
|
||||
return ip;
|
||||
}
|
||||
return request.getRemoteAddr();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前请求是否是并发请求,如果不是并发请求,将同时抢占该请求的占用标记.
|
||||
* 调用者无需主动释放并发请求标记(requestKey),因其会自动过期.
|
||||
*
|
||||
* @param redisHandler
|
||||
* @param requestKey
|
||||
* @return 返回 true 代表是并发请求,返回 false 代表不是并发请求
|
||||
*/
|
||||
protected boolean checkConcurrentRequest(RedisHandler redisHandler, String requestKey, int maxHoldSeconds, ConcurrentQequestHandleStrategy strategy) {
|
||||
if (redisHandler == null || StrUtil.isBlank(requestKey)) {
|
||||
|
||||
return false;
|
||||
}
|
||||
if (maxHoldSeconds <= 0) {
|
||||
maxHoldSeconds = 1;
|
||||
}
|
||||
|
||||
String cacheKey = "LOCK_CONCURRENT_REQUEST:" + requestKey;
|
||||
boolean lockResult = redisHandler.lock(cacheKey, maxHoldSeconds);
|
||||
if (lockResult) {
|
||||
// 没有冲突,代表不是并发请求
|
||||
return false;
|
||||
} else {
|
||||
// 存在冲突,代表是并发请求,将根据策略来处理并发请求
|
||||
if (strategy == ConcurrentQequestHandleStrategy.RETURN_NONE_WAIT) {
|
||||
return true;
|
||||
} else if (strategy == ConcurrentQequestHandleStrategy.SLEEP_THEN_RETURN) {
|
||||
// 默认睡眠 1 秒然后允许请求继续执行
|
||||
long sleepMillionSeconds = 1000L;
|
||||
int leftSeconds = redisHandler.ttl(cacheKey);
|
||||
if (leftSeconds == 0 || leftSeconds == -2) {
|
||||
// key 不存在,但是前面因为是 key 冲突 + 时间精度是秒钟,不是毫秒,还是建议等 1 秒钟
|
||||
} else if (leftSeconds > 0) {
|
||||
sleepMillionSeconds = 1000L * (long)leftSeconds;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(sleepMillionSeconds);
|
||||
} catch (Exception e) {
|
||||
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将指定币种的值转化成 USDT 币种对应的金额.
|
||||
*
|
||||
* @param amount
|
||||
* @param coinType
|
||||
* @return
|
||||
*/
|
||||
protected double compute2UsdtAmount(double amount, String coinType) {
|
||||
if (StrUtil.isBlank(coinType)) {
|
||||
throw new BusinessException("参数错误");
|
||||
}
|
||||
|
||||
double fee = 0.0;
|
||||
HobiDataService hobiDataService = wac.getBean(HobiDataService.class);
|
||||
|
||||
if (coinType.equalsIgnoreCase("BTC")) {
|
||||
fee = Double.parseDouble(hobiDataService.getSymbolRealPrize("btc"));
|
||||
} else if (coinType.equalsIgnoreCase("ETH")) {
|
||||
fee = Double.parseDouble(hobiDataService.getSymbolRealPrize("eth"));
|
||||
} else {
|
||||
// USDT、USDC 币种也支持 ERC20 类型的链,经同事确认也是比率 1:1
|
||||
fee = 1;
|
||||
}
|
||||
// 这里不就行四舍五入而是进行舍去
|
||||
return Arith.mul(amount, fee, 6);
|
||||
}
|
||||
|
||||
public String getCallback() {
|
||||
return callback;
|
||||
}
|
||||
|
||||
public void setCallback(String callback) {
|
||||
this.callback = callback;
|
||||
}
|
||||
|
||||
}
|
||||
58
comm/Kernel/src/kernel/web/ChangLanAction.java
Executable file
58
comm/Kernel/src/kernel/web/ChangLanAction.java
Executable file
@@ -0,0 +1,58 @@
|
||||
//package kernel.web;
|
||||
//
|
||||
//import java.util.Locale;
|
||||
//import java.util.Map;
|
||||
//
|
||||
//import org.apache.struts2.interceptor.SessionAware;
|
||||
//
|
||||
//import com.opensymphony.xwork2.ActionContext;
|
||||
//import com.opensymphony.xwork2.ActionSupport;
|
||||
//
|
||||
//import kernel.util.StringUtils;
|
||||
//
|
||||
//public class ChangLanAction extends ActionSupport implements SessionAware {
|
||||
// private static final long serialVersionUID = 7706343988848481176L;
|
||||
//
|
||||
// private String local;
|
||||
//
|
||||
// private Map<String, Object> session;
|
||||
//
|
||||
// public static final String WW_TRANS_I18N_LOCALE = "WW_TRANS_I18N_LOCALE";
|
||||
//
|
||||
// public void setSession(Map<String, Object> session) {
|
||||
// this.session = session;
|
||||
// }
|
||||
//
|
||||
// public void locale() {
|
||||
// Locale locale = ActionContext.getContext().getLocale();
|
||||
// if (locale == null) {
|
||||
// locale = Locale.TRADITIONAL_CHINESE;
|
||||
// ActionContext.getContext().setLocale(locale);
|
||||
// this.session.put("WW_TRANS_I18N_LOCALE", locale);
|
||||
// }
|
||||
// if (!StringUtils.isNullOrEmpty(this.local)) {
|
||||
// locale = null;
|
||||
// if (this.local.equals("zh_CN")) {
|
||||
// locale = Locale.CHINA;
|
||||
// } else if (this.local.equals("en_US")) {
|
||||
// locale = Locale.US;
|
||||
// } else if (this.local.equals("zh_TW")) {
|
||||
// locale = Locale.TAIWAN;
|
||||
// } else if (this.local.equals("ko_KR")) {
|
||||
// locale = Locale.KOREA;
|
||||
// }
|
||||
// if (locale != null) {
|
||||
// ActionContext.getContext().setLocale(locale);
|
||||
// this.session.put("WW_TRANS_I18N_LOCALE", locale);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public String getLocal() {
|
||||
// return this.local;
|
||||
// }
|
||||
//
|
||||
// public void setLocal(String local) {
|
||||
// this.local = local;
|
||||
// }
|
||||
//}
|
||||
46
comm/Kernel/src/kernel/web/I18NRequestWrapper.java
Executable file
46
comm/Kernel/src/kernel/web/I18NRequestWrapper.java
Executable file
@@ -0,0 +1,46 @@
|
||||
/* */ package kernel.web;
|
||||
|
||||
/* */
|
||||
/* */ import java.util.Locale;
|
||||
|
||||
/* */ import javax.servlet.http.HttpServletRequest;
|
||||
/* */ import javax.servlet.http.HttpServletRequestWrapper;
|
||||
/* */ import javax.servlet.http.HttpSession;
|
||||
|
||||
/* */
|
||||
/* */ public class I18NRequestWrapper extends HttpServletRequestWrapper
|
||||
/* */ {
|
||||
/* 10 */ private Locale locale = null;
|
||||
|
||||
/* */
|
||||
/* */ public I18NRequestWrapper(HttpServletRequest request) {
|
||||
/* 13 */ super(request);
|
||||
/* 14 */ HttpSession session = request.getSession();
|
||||
/* 15 */ Object object = session.getAttribute("WW_TRANS_I18N_LOCALE");
|
||||
/* 16 */ if (object != null) {
|
||||
/* 17 */ this.locale = ((Locale) session.getAttribute("WW_TRANS_I18N_LOCALE"));
|
||||
/* */ }
|
||||
/* */ else/* 20 */ this.locale = Locale.TAIWAN;
|
||||
/* */ }
|
||||
|
||||
/* */
|
||||
/* */ public String getHeader(String name)
|
||||
/* */ {
|
||||
/* 30 */ String value = super.getHeader(name);
|
||||
/* 31 */ if (("Accept-Language".equals(name)) && (this.locale != null)) {
|
||||
/* 32 */ value = this.locale.getLanguage() + "_" + this.locale.getCountry()
|
||||
+ value.substring(6, value.length());
|
||||
/* */ }
|
||||
/* 34 */ return value;
|
||||
/* */ }
|
||||
|
||||
/* */
|
||||
/* */ public Locale getLocale()
|
||||
/* */ {
|
||||
/* 39 */ if (this.locale != null) {
|
||||
/* 40 */ return this.locale;
|
||||
/* */ }
|
||||
/* 42 */ return super.getLocale();
|
||||
/* */ }
|
||||
/* */ }
|
||||
|
||||
32
comm/Kernel/src/kernel/web/I18nFilter.java
Executable file
32
comm/Kernel/src/kernel/web/I18nFilter.java
Executable file
@@ -0,0 +1,32 @@
|
||||
/* */ package kernel.web;
|
||||
/* */
|
||||
/* */ 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 javax.servlet.http.HttpServletRequest;
|
||||
/* */
|
||||
/* */ public class I18nFilter
|
||||
/* */ implements Filter
|
||||
/* */ {
|
||||
/* */ public void destroy()
|
||||
/* */ {
|
||||
/* */ }
|
||||
/* */
|
||||
/* */ public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
|
||||
/* */ throws IOException, ServletException
|
||||
/* */ {
|
||||
/* 24 */ HttpServletRequest r = (HttpServletRequest)req;
|
||||
/* 25 */ I18NRequestWrapper request = new I18NRequestWrapper(r);
|
||||
/* 26 */ filterChain.doFilter(request, resp);
|
||||
/* */ }
|
||||
/* */
|
||||
/* */ public void init(FilterConfig arg0)
|
||||
/* */ throws ServletException
|
||||
/* */ {
|
||||
/* */ }
|
||||
/* */ }
|
||||
|
||||
104
comm/Kernel/src/kernel/web/JdbcTemplateWithPaging.java
Executable file
104
comm/Kernel/src/kernel/web/JdbcTemplateWithPaging.java
Executable file
@@ -0,0 +1,104 @@
|
||||
package kernel.web;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.apache.commons.lang.ArrayUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
|
||||
|
||||
public class JdbcTemplateWithPaging {
|
||||
private static final Logger logger = LoggerFactory.getLogger(JdbcTemplateWithPaging.class);
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
private NamedParameterJdbcOperations namedParameterJdbcTemplate;
|
||||
|
||||
public List<Map<String, Object>> queryPage(String sql, Object[] args, int start, int limit) {
|
||||
if ((start <= 0) && (limit <= 0)) {
|
||||
return this.jdbcTemplate.queryForList(sql, args);
|
||||
}
|
||||
if (start <= 1) {
|
||||
sql = getLimitString(sql, false);
|
||||
args = ArrayUtils.add(args, args.length, Integer.valueOf(limit));
|
||||
} else {
|
||||
sql = getLimitString(sql, true);
|
||||
args = ArrayUtils.add(args, args.length, Integer.valueOf(start + limit));
|
||||
args = ArrayUtils.add(args, args.length, Integer.valueOf(start));
|
||||
}
|
||||
|
||||
logger.info("paging sql : \n" + sql);
|
||||
return this.jdbcTemplate.queryForList(sql, args);
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> queryPage(String sql, int start, int limit) {
|
||||
Object[] args = new Object[0];
|
||||
return queryPage(sql, args, start, limit);
|
||||
}
|
||||
|
||||
public <T> List<T> queryPage(String sql, int start, int limit, RowMapper<T> rowMapper) throws DataAccessException {
|
||||
if ((start <= 0) && (limit <= 0)) {
|
||||
return this.jdbcTemplate.query(sql, rowMapper);
|
||||
}
|
||||
Object[] args = new Object[0];
|
||||
if (start <= 1) {
|
||||
sql = getLimitString(sql, false);
|
||||
args = ArrayUtils.add(args, args.length, Integer.valueOf(limit));
|
||||
} else {
|
||||
sql = getLimitString(sql, true);
|
||||
args = ArrayUtils.add(args, args.length, Integer.valueOf(start + limit));
|
||||
args = ArrayUtils.add(args, args.length, Integer.valueOf(start));
|
||||
}
|
||||
|
||||
Pattern pattern = Pattern.compile("\\?");
|
||||
|
||||
Matcher matcher = pattern.matcher(sql);
|
||||
|
||||
for (int i = 0; i < args.length; matcher = pattern.matcher(sql)) {
|
||||
sql = matcher.replaceFirst(args[i].toString());
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
logger.info("paging sql : \n" + sql);
|
||||
return this.jdbcTemplate.query(sql, rowMapper);
|
||||
}
|
||||
|
||||
private String getLimitString(String sql, boolean hasOffset) {
|
||||
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 (hasOffset) {
|
||||
pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
|
||||
} else {
|
||||
pagingSelect.append("select * from ( ");
|
||||
}
|
||||
pagingSelect.append(sql);
|
||||
if (hasOffset) {
|
||||
pagingSelect.append(" ) row_ where rownum <= ?) where rownum_ > ?");
|
||||
} else {
|
||||
pagingSelect.append(" ) where rownum <= ?");
|
||||
}
|
||||
|
||||
if (isForUpdate) {
|
||||
pagingSelect.append(" for update");
|
||||
}
|
||||
return pagingSelect.toString();
|
||||
}
|
||||
|
||||
public int queryCountBySql(String sqlStr) {
|
||||
return ((Integer) this.jdbcTemplate.queryForObject(sqlStr, Integer.class)).intValue();
|
||||
}
|
||||
|
||||
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
}
|
||||
58
comm/Kernel/src/kernel/web/LanguageAction.java
Executable file
58
comm/Kernel/src/kernel/web/LanguageAction.java
Executable file
@@ -0,0 +1,58 @@
|
||||
//package kernel.web;
|
||||
//
|
||||
//import java.util.Locale;
|
||||
//import java.util.Map;
|
||||
//
|
||||
//import org.apache.struts2.interceptor.SessionAware;
|
||||
//
|
||||
//import com.opensymphony.xwork2.ActionContext;
|
||||
//import com.opensymphony.xwork2.ActionSupport;
|
||||
//
|
||||
//import kernel.util.StringUtils;
|
||||
//
|
||||
//public class LanguageAction extends ActionSupport implements SessionAware {
|
||||
// private static final long serialVersionUID = 7706343988848481176L;
|
||||
//
|
||||
// private String local;
|
||||
//
|
||||
// private Map<String, Object> session;
|
||||
//
|
||||
// public static final String WW_TRANS_I18N_LOCALE = "WW_TRANS_I18N_LOCALE";
|
||||
//
|
||||
// public void setSession(Map<String, Object> session) {
|
||||
// this.session = session;
|
||||
// }
|
||||
//
|
||||
// public void locale() {
|
||||
// Locale locale = ActionContext.getContext().getLocale();
|
||||
// if (locale == null) {
|
||||
// locale = Locale.TRADITIONAL_CHINESE;
|
||||
// ActionContext.getContext().setLocale(locale);
|
||||
// this.session.put("WW_TRANS_I18N_LOCALE", locale);
|
||||
// }
|
||||
// if (!StringUtils.isNullOrEmpty(this.local)) {
|
||||
// locale = null;
|
||||
// if (this.local.equals("zh_CN")) {
|
||||
// locale = Locale.CHINA;
|
||||
// } else if (this.local.equals("en_US")) {
|
||||
// locale = Locale.US;
|
||||
// } else if (this.local.equals("zh_TW")) {
|
||||
// locale = Locale.TAIWAN;
|
||||
// } else if (this.local.equals("ko_KR")) {
|
||||
// locale = Locale.KOREA;
|
||||
// }
|
||||
// if (locale != null) {
|
||||
// ActionContext.getContext().setLocale(locale);
|
||||
// this.session.put("WW_TRANS_I18N_LOCALE", locale);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public String getLocal() {
|
||||
// return this.local;
|
||||
// }
|
||||
//
|
||||
// public void setLocal(String local) {
|
||||
// this.local = local;
|
||||
// }
|
||||
//}
|
||||
114
comm/Kernel/src/kernel/web/Page.java
Executable file
114
comm/Kernel/src/kernel/web/Page.java
Executable file
@@ -0,0 +1,114 @@
|
||||
package kernel.web;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Page implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private List elements = new ArrayList();
|
||||
|
||||
private int pageSize = 10;
|
||||
public static final int DEFAULT_PAGE_SIZE = 10;
|
||||
private int thisPageNumber = 1;
|
||||
|
||||
private int totalElements = 0;
|
||||
|
||||
public static final Page EMPTY_PAGE = new Page();
|
||||
|
||||
public Page() {
|
||||
}
|
||||
|
||||
public void setPageSize(int pageSize) {
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
|
||||
public void setThisPageNumber(int thisPageNumber) {
|
||||
if (thisPageNumber > 0) {
|
||||
this.thisPageNumber = thisPageNumber;
|
||||
}
|
||||
if (this.thisPageNumber > getTotalPage())
|
||||
this.thisPageNumber = getTotalPage();
|
||||
}
|
||||
|
||||
public Page(int thisPageNumber, int pageSize, int totalElements) {
|
||||
if (thisPageNumber > 0) {
|
||||
this.thisPageNumber = thisPageNumber;
|
||||
}
|
||||
if (pageSize > 0) {
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
if (totalElements >= 0)
|
||||
this.totalElements = totalElements;
|
||||
}
|
||||
|
||||
public boolean isFirstPage() {
|
||||
return getThisPageNumber() == 1;
|
||||
}
|
||||
|
||||
public boolean isLastPage() {
|
||||
return getThisPageNumber() >= getTotalPage();
|
||||
}
|
||||
|
||||
public boolean hasNextPage() {
|
||||
return getTotalPage() > getThisPageNumber();
|
||||
}
|
||||
|
||||
public boolean hasPreviousPage() {
|
||||
return getThisPageNumber() > 1;
|
||||
}
|
||||
|
||||
public int getTotalPage() {
|
||||
return this.totalElements % this.pageSize == 0 ? this.totalElements / this.pageSize
|
||||
: this.totalElements / this.pageSize + 1;
|
||||
}
|
||||
|
||||
public List getElements() {
|
||||
return this.elements;
|
||||
}
|
||||
|
||||
public void setElements(List elements) {
|
||||
this.elements = elements;
|
||||
}
|
||||
|
||||
public int getTotalElements() {
|
||||
return this.totalElements;
|
||||
}
|
||||
|
||||
public void setTotalElements(int totalElements) {
|
||||
if (totalElements >= 0) {
|
||||
this.totalElements = totalElements;
|
||||
}
|
||||
if (this.thisPageNumber > getTotalPage())
|
||||
this.thisPageNumber = getTotalPage();
|
||||
}
|
||||
|
||||
public int getFirstElementNumber() {
|
||||
return (getThisPageNumber() - 1) * getPageSize();
|
||||
}
|
||||
|
||||
public int getLastElementNumber() {
|
||||
int fullPage = getFirstElementNumber() + getPageSize() - 1;
|
||||
return getTotalElements() < fullPage ? getTotalElements() : fullPage;
|
||||
}
|
||||
|
||||
public int getNextPageNumber() {
|
||||
return getThisPageNumber() + 1;
|
||||
}
|
||||
|
||||
public int getPreviousPageNumber() {
|
||||
return getThisPageNumber() - 1;
|
||||
}
|
||||
|
||||
public int getPageSize() {
|
||||
return this.pageSize;
|
||||
}
|
||||
|
||||
public int getThisPageNumber() {
|
||||
return this.thisPageNumber;
|
||||
}
|
||||
|
||||
public int getFirstPage() {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
111
comm/Kernel/src/kernel/web/PageActionSupport.java
Executable file
111
comm/Kernel/src/kernel/web/PageActionSupport.java
Executable file
@@ -0,0 +1,111 @@
|
||||
package kernel.web;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import kernel.util.StringUtils;
|
||||
import security.web.BaseSecurityAction;
|
||||
|
||||
public class PageActionSupport extends BaseSecurityAction {
|
||||
|
||||
/**
|
||||
* Member Description
|
||||
*/
|
||||
|
||||
private static final long serialVersionUID = -27853059031238999L;
|
||||
|
||||
protected Page page;
|
||||
|
||||
protected List<Integer> tabs;
|
||||
|
||||
protected int pageNo = 1;
|
||||
|
||||
protected int pageSize = 10;
|
||||
|
||||
/**
|
||||
* 检查并设置pageNo
|
||||
*/
|
||||
public void checkAndSetPageNo(String pageNoStr) {
|
||||
|
||||
if (StringUtils.isNullOrEmpty(pageNoStr)) {
|
||||
this.pageNo = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
|
||||
Matcher isNum = pattern.matcher(pageNoStr);
|
||||
if (!isNum.matches()) {
|
||||
this.pageNo = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
int pageNo = Integer.valueOf(pageNoStr).intValue();
|
||||
if (pageNo <= 0) {
|
||||
this.pageNo = 1;
|
||||
} else {
|
||||
this.pageNo = pageNo;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
public List<Integer> bulidTabs() {
|
||||
List<Integer> tabs = new ArrayList<Integer>();
|
||||
if (page == null) {
|
||||
return tabs;
|
||||
}
|
||||
int pageCount = 10;
|
||||
|
||||
int thisPageNumber = page.getThisPageNumber();
|
||||
for (int i = 5; i > 0; i--) {
|
||||
if ((thisPageNumber - i) > 0) {
|
||||
tabs.add(thisPageNumber - i);
|
||||
pageCount--;
|
||||
}
|
||||
}
|
||||
tabs.add(thisPageNumber);
|
||||
for (int i = pageCount; i > 0; i--) {
|
||||
if ((thisPageNumber + i) <= page.getTotalPage()) {
|
||||
tabs.add(thisPageNumber + i);
|
||||
}
|
||||
|
||||
}
|
||||
Collections.sort(tabs, new Comparator<Integer>() {
|
||||
public int compare(Integer arg0, Integer arg1) {
|
||||
return arg0.compareTo(arg1);
|
||||
}
|
||||
});
|
||||
|
||||
return tabs;
|
||||
}
|
||||
|
||||
public List<Integer> getTabs() {
|
||||
return tabs;
|
||||
}
|
||||
|
||||
public Page getPage() {
|
||||
return page;
|
||||
}
|
||||
|
||||
public void setPage(Page page) {
|
||||
this.page = page;
|
||||
}
|
||||
|
||||
public int getPageNo() {
|
||||
return pageNo;
|
||||
}
|
||||
|
||||
public void setPageNo(int pageNo) {
|
||||
this.pageNo = pageNo;
|
||||
}
|
||||
|
||||
protected void setPageSize(int pageSize) {
|
||||
this.pageSize = pageSize;
|
||||
}
|
||||
|
||||
}
|
||||
16
comm/Kernel/src/kernel/web/PagedQueryDao.java
Executable file
16
comm/Kernel/src/kernel/web/PagedQueryDao.java
Executable file
@@ -0,0 +1,16 @@
|
||||
package kernel.web;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public interface PagedQueryDao {
|
||||
/**
|
||||
* HQL分页 不计算分页标签
|
||||
*/
|
||||
public Page pagedQueryHql(int pageNo, int pageSize, String queryString, Map<String, Object> parameters);
|
||||
|
||||
/**
|
||||
* SQL分页 不计算分页标签
|
||||
* 返回的记录集合是 List<Map>
|
||||
*/
|
||||
public Page pagedQuerySQL(int pageNo, int pageSize, String queryString, Map<String, Object> parameters);
|
||||
}
|
||||
43
comm/Kernel/src/kernel/web/PagedQueryDaoImpl.java
Executable file
43
comm/Kernel/src/kernel/web/PagedQueryDaoImpl.java
Executable file
@@ -0,0 +1,43 @@
|
||||
package kernel.web;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.hibernate.Query;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
|
||||
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
|
||||
|
||||
import kernel.dao.HibernateUtils;
|
||||
|
||||
public class PagedQueryDaoImpl extends HibernateDaoSupport implements PagedQueryDao {
|
||||
private NamedParameterJdbcOperations namedParameterJdbcTemplate;
|
||||
|
||||
public Page pagedQueryHql(int pageNo, int pageSize, String queryString, Map<String, Object> parameters) {
|
||||
Page page = new Page(pageNo, pageSize, Integer.MAX_VALUE);
|
||||
|
||||
Query query = currentSession().createQuery(queryString);
|
||||
HibernateUtils.applyParameters(query, parameters);
|
||||
query.setFirstResult(page.getFirstElementNumber());
|
||||
query.setMaxResults(pageSize);
|
||||
List list = query.list();
|
||||
page.setElements(list);
|
||||
return page;
|
||||
}
|
||||
|
||||
public Page pagedQuerySQL(int pageNo, int pageSize, String queryString, Map<String, Object> parameters) {
|
||||
if (pageNo <= 0) {
|
||||
pageNo = 1;
|
||||
}
|
||||
Page page = new Page(pageNo, pageSize, Integer.MAX_VALUE);
|
||||
queryString = queryString + " limit " + (pageNo - 1) * pageSize + "," + pageSize;
|
||||
List<Map<String, Object>> list = namedParameterJdbcTemplate.queryForList(queryString.toString(), parameters);
|
||||
|
||||
page.setElements(list);
|
||||
return page;
|
||||
}
|
||||
|
||||
public void setNamedParameterJdbcTemplate(NamedParameterJdbcOperations namedParameterJdbcTemplate) {
|
||||
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
|
||||
}
|
||||
|
||||
}
|
||||
31
comm/Kernel/src/kernel/web/RequestParseFilter.java
Executable file
31
comm/Kernel/src/kernel/web/RequestParseFilter.java
Executable file
@@ -0,0 +1,31 @@
|
||||
// package kernel.web;
|
||||
//
|
||||
// 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 javax.servlet.http.HttpServletRequest;
|
||||
// import org.apache.struts2.dispatcher.StrutsRequestWrapper;
|
||||
//
|
||||
// public class RequestParseFilter
|
||||
// implements Filter
|
||||
// {
|
||||
// public void destroy()
|
||||
// {
|
||||
// }
|
||||
//
|
||||
// public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
|
||||
// throws IOException, ServletException
|
||||
// {
|
||||
///* 25 */ chain.doFilter(new StrutsRequestWrapper((HttpServletRequest)request), response);
|
||||
// }
|
||||
//
|
||||
// public void init(FilterConfig arg0)
|
||||
// throws ServletException
|
||||
// {
|
||||
// }
|
||||
// }
|
||||
//
|
||||
14
comm/Kernel/src/kernel/web/RequestParseWrapper.java
Executable file
14
comm/Kernel/src/kernel/web/RequestParseWrapper.java
Executable file
@@ -0,0 +1,14 @@
|
||||
//package kernel.web;
|
||||
//
|
||||
//import java.io.IOException;
|
||||
//import javax.servlet.http.HttpServletRequest;
|
||||
//import org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest;
|
||||
//
|
||||
//public class RequestParseWrapper extends JakartaMultiPartRequest
|
||||
//{
|
||||
// public void parse(HttpServletRequest servletRequest, String saveDir)
|
||||
// throws IOException
|
||||
// {
|
||||
// }
|
||||
//}
|
||||
//
|
||||
35
comm/Kernel/src/kernel/web/ResultObject.java
Executable file
35
comm/Kernel/src/kernel/web/ResultObject.java
Executable file
@@ -0,0 +1,35 @@
|
||||
package kernel.web;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class ResultObject implements Serializable {
|
||||
private static final long serialVersionUID = 6952247764513362272L;
|
||||
private String code = "0";
|
||||
private String msg;
|
||||
private Object data;
|
||||
|
||||
public String getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public Object getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(Object data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
}
|
||||
72
comm/Kernel/src/kernel/web/ShowImgAction.java
Executable file
72
comm/Kernel/src/kernel/web/ShowImgAction.java
Executable file
@@ -0,0 +1,72 @@
|
||||
package kernel.web;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Properties;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
// import org.apache.struts2.ServletActionContext;
|
||||
|
||||
import kernel.util.ImageDispatcher;
|
||||
import kernel.util.PropertiesLoaderUtils;
|
||||
|
||||
public class ShowImgAction extends BaseAction {
|
||||
private static final long serialVersionUID = 7683481061134646641L;
|
||||
private static Properties properties = PropertiesLoaderUtils.loadProperties("config/system.properties");
|
||||
|
||||
protected String imagePath = null;
|
||||
|
||||
// public String showImg() {
|
||||
// HttpServletResponse response = ServletActionContext.getResponse();
|
||||
// response.setContentType("application/json;charset=UTF-8");
|
||||
// response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
// response.setHeader("Access-Control-Allow-Headers", "content-type, x-requested-with");
|
||||
// response.setHeader("Access-Control-Allow-Credentials", "true");
|
||||
// String strForward = "success";
|
||||
// return strForward;
|
||||
// }
|
||||
//
|
||||
// public String view() {
|
||||
// return "view";
|
||||
// }
|
||||
//
|
||||
// public InputStream getDownloadFile() throws FileNotFoundException {
|
||||
// BufferedInputStream bis = null;
|
||||
// try {
|
||||
// boolean goback = false;
|
||||
// File fl = null;
|
||||
// if ((this.imagePath == null) || (this.imagePath.trim().length() <= 0)) {
|
||||
// fl = new File(properties.getProperty("images.dir") + "noimage.jpg");
|
||||
// goback = true;
|
||||
// }
|
||||
// if (!goback) {
|
||||
// fl = ImageDispatcher.findFile(this.imagePath);
|
||||
// if (fl == null) {
|
||||
// fl = new File(properties.getProperty("images.dir") + "noimage.jpg");
|
||||
// }
|
||||
// if (!fl.exists()) {
|
||||
// fl = new File(properties.getProperty("images.dir") + "noimage.jpg");
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// FileInputStream fis = new FileInputStream(fl);
|
||||
// bis = new BufferedInputStream(fis);
|
||||
// } catch (Throwable localThrowable) {
|
||||
// }
|
||||
//
|
||||
// return bis;
|
||||
// }
|
||||
|
||||
public String getImagePath() {
|
||||
return this.imagePath;
|
||||
}
|
||||
|
||||
public void setImagePath(String imagePath) {
|
||||
this.imagePath = imagePath;
|
||||
}
|
||||
}
|
||||
125
comm/Kernel/src/kernel/web/UploadImgAction.java
Executable file
125
comm/Kernel/src/kernel/web/UploadImgAction.java
Executable file
@@ -0,0 +1,125 @@
|
||||
package kernel.web;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Properties;
|
||||
import java.util.Random;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
// import org.apache.struts2.ServletActionContext;
|
||||
|
||||
import kernel.util.JsonUtils;
|
||||
import kernel.util.PropertiesLoaderUtils;
|
||||
|
||||
public class UploadImgAction extends BaseAction {
|
||||
private static Log logger = LogFactory.getLog(UploadImgAction.class);
|
||||
private static final long serialVersionUID = 4590792756444167149L;
|
||||
private File file;
|
||||
private static Properties properties = PropertiesLoaderUtils.loadProperties("config/system.properties");
|
||||
|
||||
// public String execute() throws IOException {
|
||||
// HttpServletResponse response = ServletActionContext.getResponse();
|
||||
// response.setContentType("application/json;charset=UTF-8");
|
||||
// response.setHeader("Access-Control-Allow-Origin", "*");
|
||||
// ResultObject resultObject = new ResultObject();
|
||||
// PrintWriter out = response.getWriter();
|
||||
//
|
||||
// try {
|
||||
//
|
||||
// String fileFileName = file.getName();
|
||||
//
|
||||
// HashMap extMap = new HashMap();
|
||||
// extMap.put("image", "jpg,png");
|
||||
// if (this.file.length() / 1024L > 30720L) {
|
||||
// this.error = "图片大小不能超过30M";
|
||||
//
|
||||
// resultObject.setCode("1");
|
||||
// resultObject.setMsg(error);
|
||||
// this.result = JsonUtils.getJsonString(resultObject);
|
||||
// out.println(this.result);
|
||||
// return null;
|
||||
// }
|
||||
// SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
|
||||
// String ymd = sdf.format(new Date());
|
||||
//
|
||||
// String fileDir = properties.getProperty("images.dir");
|
||||
// File f = new File(fileDir + "/" + ymd);
|
||||
// if ((!f.exists()) && (!f.mkdirs())) {
|
||||
// this.error = ("文件:" + fileDir + "创建失败!");
|
||||
// resultObject.setCode("1");
|
||||
// resultObject.setMsg("服务器错误");
|
||||
// logger.warn(error);
|
||||
// this.result = JsonUtils.getJsonString(resultObject);
|
||||
// out.println(this.result);
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
//// String fileExt = fileFileName.substring(fileFileName.lastIndexOf(".") + 1).toLowerCase();
|
||||
//// if (!Arrays.asList(((String) extMap.get("image")).split(",")).contains(fileExt)) {
|
||||
////// this.error = ("上传图片是不允许的扩展名。\n只允许" + (String) extMap.get("image") + "格式。");
|
||||
////// resultObject.setCode("1");
|
||||
////// resultObject.setMsg(error);
|
||||
////// this.result = JsonUtils.getJsonString(resultObject);
|
||||
////// out.println(this.result);
|
||||
////// return null;
|
||||
//// }
|
||||
//
|
||||
// String imagePath = "";
|
||||
// SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
|
||||
// String yms = sdf2.format(new Date());
|
||||
//
|
||||
// String imageDir = ymd + "/" + yms + new Random().nextInt(10000000) + "." + "png";
|
||||
// imagePath = fileDir + imageDir.toLowerCase().trim();
|
||||
//
|
||||
// FileInputStream in = new FileInputStream(this.file);
|
||||
//
|
||||
// FileOutputStream outputStream = new FileOutputStream(imagePath);
|
||||
//
|
||||
// BufferedInputStream inputStream = new BufferedInputStream(in);
|
||||
// byte[] buf = new byte[1024];
|
||||
// int length = 0;
|
||||
// while ((length = inputStream.read(buf)) != -1) {
|
||||
// outputStream.write(buf, 0, length);
|
||||
// }
|
||||
// resultObject.setData(imageDir);
|
||||
// } catch (FileNotFoundException e) {
|
||||
// this.error = "文件上传失败";
|
||||
// resultObject.setCode("1");
|
||||
// resultObject.setMsg("服务器错误");
|
||||
// logger.error(error, e);
|
||||
// this.result = JsonUtils.getJsonString(resultObject);
|
||||
// out.println(this.result);
|
||||
// return null;
|
||||
// } catch (Exception e) {
|
||||
// this.error = "文件上传失败";
|
||||
//
|
||||
// resultObject.setCode("1");
|
||||
// resultObject.setMsg("服务器错误");
|
||||
// logger.error(error, e);
|
||||
// this.result = JsonUtils.getJsonString(resultObject);
|
||||
// out.println(this.result);
|
||||
// return null;
|
||||
//
|
||||
// }
|
||||
//
|
||||
// this.result = JsonUtils.getJsonString(resultObject);
|
||||
// out.println(this.result);
|
||||
// return null;
|
||||
// }
|
||||
|
||||
public void setFile(File file) {
|
||||
this.file = file;
|
||||
}
|
||||
|
||||
}
|
||||
38
comm/Kernel/src/kernel/web/Web114Filter.java
Executable file
38
comm/Kernel/src/kernel/web/Web114Filter.java
Executable file
@@ -0,0 +1,38 @@
|
||||
package kernel.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Locale;
|
||||
|
||||
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 javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import kernel.util.StringUtils;
|
||||
|
||||
public class Web114Filter implements Filter {
|
||||
public void destroy() {
|
||||
}
|
||||
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
|
||||
throws IOException, ServletException {
|
||||
String contentType = request.getContentType();
|
||||
if (!StringUtils.isNullOrEmpty(contentType)) {
|
||||
contentType = contentType.toLowerCase(Locale.ENGLISH);
|
||||
if ((contentType != null) && (contentType.contains("multipart/form-data"))
|
||||
&& (!contentType.startsWith("multipart/form-data"))) {
|
||||
response.getWriter().write("Reject!");
|
||||
} else {
|
||||
filterChain.doFilter(new Web114RequestWrapper((HttpServletRequest) request), response);
|
||||
}
|
||||
} else {
|
||||
filterChain.doFilter(new Web114RequestWrapper((HttpServletRequest) request), response);
|
||||
}
|
||||
}
|
||||
|
||||
public void init(FilterConfig arg0) throws ServletException {
|
||||
}
|
||||
}
|
||||
45
comm/Kernel/src/kernel/web/Web114RequestWrapper.java
Executable file
45
comm/Kernel/src/kernel/web/Web114RequestWrapper.java
Executable file
@@ -0,0 +1,45 @@
|
||||
/* */ package kernel.web;
|
||||
/* */
|
||||
/* */ import javax.servlet.http.HttpServletRequest;
|
||||
/* */ import javax.servlet.http.HttpServletRequestWrapper;
|
||||
/* */ import org.apache.commons.lang.StringEscapeUtils;
|
||||
/* */
|
||||
/* */ public class Web114RequestWrapper extends HttpServletRequestWrapper
|
||||
/* */ {
|
||||
/* */ public Web114RequestWrapper(HttpServletRequest request)
|
||||
/* */ {
|
||||
/* 13 */ super(request);
|
||||
/* */ }
|
||||
/* */
|
||||
/* */ public String getParameter(String name)
|
||||
/* */ {
|
||||
/* 19 */ String value = super.getParameter(name);
|
||||
/* 20 */ if ((!name.equals("BPassportLoginResponse")) && (!name.equals("BPassportCheckResponse")) && (value != null)) {
|
||||
/* 21 */ value = filterUserInput(value);
|
||||
/* */ }
|
||||
/* 23 */ return value;
|
||||
/* */ }
|
||||
/* */
|
||||
/* */ public String[] getParameterValues(String name)
|
||||
/* */ {
|
||||
/* 29 */ String[] values = super.getParameterValues(name);
|
||||
/* 30 */ if (values != null)
|
||||
/* */ {
|
||||
/* 32 */ int i = 0; for (int l = values.length; i < l; i++)
|
||||
/* */ {
|
||||
/* 34 */ values[i] = filterUserInput(values[i]);
|
||||
/* */ }
|
||||
/* */ }
|
||||
/* 37 */ return values;
|
||||
/* */ }
|
||||
/* */
|
||||
/* */ private String filterUserInput(String input)
|
||||
/* */ {
|
||||
/* 51 */ input = StringEscapeUtils.escapeSql(input);
|
||||
/* 52 */ input = StringEscapeUtils.escapeHtml(input);
|
||||
/* 53 */ input = StringEscapeUtils.escapeJavaScript(input);
|
||||
/* */
|
||||
/* 55 */ return input;
|
||||
/* */ }
|
||||
/* */ }
|
||||
|
||||
80
comm/Kernel/src/project/web/api/UploadImgController.java
Executable file
80
comm/Kernel/src/project/web/api/UploadImgController.java
Executable file
@@ -0,0 +1,80 @@
|
||||
//package project.web.api.controller;
|
||||
//
|
||||
//import kernel.exception.BusinessException;
|
||||
//import kernel.util.ImageDispatcher;
|
||||
//import kernel.util.PropertiesLoaderUtils;
|
||||
//import kernel.web.ResultObject;
|
||||
//import org.apache.commons.lang3.StringUtils;
|
||||
//import org.apache.commons.logging.Log;
|
||||
//import org.apache.commons.logging.LogFactory;
|
||||
//import org.springframework.beans.factory.annotation.Autowired;
|
||||
//import org.springframework.web.bind.annotation.CrossOrigin;
|
||||
//import org.springframework.web.bind.annotation.RequestMapping;
|
||||
//import org.springframework.web.bind.annotation.RestController;
|
||||
//import org.springframework.web.multipart.MultipartFile;
|
||||
//import org.springframework.web.multipart.MultipartHttpServletRequest;
|
||||
//import org.springframework.web.multipart.MultipartResolver;
|
||||
//import org.springframework.web.multipart.commons.CommonsMultipartResolver;
|
||||
//import project.web.api.impl.AwsS3OSSFileService;
|
||||
//import project.web.api.vo.FileUploadParamsVo;
|
||||
//
|
||||
//import javax.servlet.http.HttpServletRequest;
|
||||
//import javax.servlet.http.HttpServletResponse;
|
||||
//import java.io.*;
|
||||
//import java.text.SimpleDateFormat;
|
||||
//import java.util.Date;
|
||||
//import java.util.HashMap;
|
||||
//import java.util.Properties;
|
||||
//import java.util.Random;
|
||||
//
|
||||
//@RestController
|
||||
//@CrossOrigin
|
||||
//public class UploadImgController {
|
||||
// private static Log logger = LogFactory.getLog(UploadImgController.class);
|
||||
//
|
||||
// @Autowired
|
||||
// AwsS3OSSFileService awsS3OSSFileService;
|
||||
//
|
||||
// @RequestMapping(value = "api/uploadimg!execute.action")
|
||||
// public Object execute(FileUploadParamsVo filePrams) {
|
||||
// ResultObject resultObject = new ResultObject();
|
||||
// try {
|
||||
// if (filePrams.getFile() == null || filePrams.getFile().getSize() == 0) {
|
||||
// resultObject.setCode("1");
|
||||
// resultObject.setMsg("图片不能为空");
|
||||
// return resultObject;
|
||||
// }
|
||||
// if (StringUtils.isBlank(filePrams.getModuleName())) {
|
||||
// resultObject.setCode("1");
|
||||
// resultObject.setMsg("模块名不能为空");
|
||||
// return resultObject;
|
||||
// }
|
||||
//
|
||||
// HashMap extMap = new HashMap();
|
||||
// extMap.put("image", "jpg,png");
|
||||
// if (awsS3OSSFileService.isImageFile(filePrams.getFile().getOriginalFilename())) {
|
||||
// resultObject.setCode("1");
|
||||
// resultObject.setMsg("请上传图片格式的文件");
|
||||
// return resultObject;
|
||||
// }
|
||||
// if (filePrams.getFile().getSize() / 1024L > 30720L) {
|
||||
// resultObject.setCode("1");
|
||||
// resultObject.setMsg("图片大小不能超过30M");
|
||||
// return resultObject;
|
||||
// }
|
||||
// resultObject.setData(awsS3OSSFileService.putS3Object(filePrams.getModuleName(), filePrams.getFile()));
|
||||
// } catch (BusinessException e) {
|
||||
// resultObject.setCode("1");
|
||||
// resultObject.setMsg(e.getMessage());
|
||||
// logger.error("文件上传失败", e);
|
||||
// return resultObject;
|
||||
// } catch (Exception e) {
|
||||
// resultObject.setCode("1");
|
||||
// resultObject.setMsg("服务器错误");
|
||||
// logger.error("文件上传失败", e);
|
||||
// return resultObject;
|
||||
// }
|
||||
//
|
||||
// return resultObject;
|
||||
// }
|
||||
//}
|
||||
12
comm/Kernel/src/server/Server.java
Executable file
12
comm/Kernel/src/server/Server.java
Executable file
@@ -0,0 +1,12 @@
|
||||
package server;
|
||||
|
||||
/**
|
||||
* Server生命周期服务,在应用启动和停止时调用
|
||||
*/
|
||||
public interface Server extends Comparable<Server>{
|
||||
public void start();
|
||||
public void stop();
|
||||
public void pause();
|
||||
public void restart();
|
||||
public boolean isRunning();
|
||||
}
|
||||
114
comm/Kernel/src/util/ArithmeticUtils.java
Executable file
114
comm/Kernel/src/util/ArithmeticUtils.java
Executable file
@@ -0,0 +1,114 @@
|
||||
package util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 算法工具类
|
||||
*
|
||||
* Project Name:erp-procurement-util
|
||||
* ClassName:ArithmeticUtils
|
||||
* Description:
|
||||
* @date: 2019年7月20日 上午11:57:49
|
||||
* note:
|
||||
*
|
||||
*/
|
||||
public class ArithmeticUtils {
|
||||
|
||||
/**
|
||||
* 获取N个集合的笛卡尔积
|
||||
* <p/>
|
||||
* 假如传入的字符串List为:[[1, 2, 3], [5, 6], [7, 8]]
|
||||
* a=[1, 2, 3]
|
||||
* b=[5, 6]
|
||||
* c=[7, 8]
|
||||
* 其大小分别为:a_length=3,b_length=2,c_length=2,
|
||||
* 目标list的总大小为:totalSize=3*2*2 = 12
|
||||
* 对每个子集a,b,c,进行循环次数=总记录数/(元素个数*后续集合的笛卡尔积个数)
|
||||
* 对a中的每个元素循环次数=总记录数/(元素个数*后续集合的笛卡尔积个数)=12/(3*4)=1次,每个元素每次循环打印次数:后续集合的笛卡尔积个数=2*2个
|
||||
* 对b中的每个元素循环次数=总记录数/(元素个数*后续集合的笛卡尔积个数)=12/(2*2)=3次,每个元素每次循环打印次数:后续集合的笛卡尔积个数=2个
|
||||
* 对c中的每个元素循环次数=总记录数/(元素个数*后续集合的笛卡尔积个数)=12/(2*1)=6次,每个元素每次循环打印次数:后续集合的笛卡尔积个数=1个
|
||||
* <p/>
|
||||
* 运行结果:
|
||||
* [[1, 2, 3], [5, 6], [7, 8]]
|
||||
* 1,5,7,
|
||||
* 1,5,8,
|
||||
* 1,6,7,
|
||||
* 1,6,8,
|
||||
* 2,5,7,
|
||||
* 2,5,8,
|
||||
* 2,6,7,
|
||||
* 2,6,8,
|
||||
* 3,5,7,
|
||||
* 3,5,8,
|
||||
* 3,6,7,
|
||||
* 3,6,8]
|
||||
* <p/>
|
||||
* 从结果中可以看到:
|
||||
* a中的每个元素每个元素循环1次,每次打印4个
|
||||
* b中的每个元素每个元素循环3次,每次打印2个
|
||||
* c中的每个元素每个元素循环6次,每次打印1个
|
||||
*
|
||||
* @param
|
||||
* @return 结果用逗号分隔
|
||||
*/
|
||||
public static List<List<String>> descartes(List<List<String>> strs) {
|
||||
int total = 1;
|
||||
for (int i = 0; i < strs.size(); i++) {
|
||||
total *= strs.get(i).size();
|
||||
}
|
||||
String[] myresult = new String[total];
|
||||
int now = 1;
|
||||
//每个元素每次循环打印个数
|
||||
int itemLoopNum = 1;
|
||||
//每个元素循环的总次数
|
||||
int loopPerItem = 1;
|
||||
for (int i = 0; i < strs.size(); i++) {
|
||||
List<String> temp = strs.get(i);
|
||||
now = now * temp.size();
|
||||
//目标数组的索引值
|
||||
int index = 0;
|
||||
int currentSize = temp.size();
|
||||
itemLoopNum = total / now;
|
||||
loopPerItem = total / (itemLoopNum * currentSize);
|
||||
int myindex = 0;
|
||||
for (int j = 0; j < temp.size(); j++) {
|
||||
|
||||
//每个元素循环的总次数
|
||||
for (int k = 0; k < loopPerItem; k++) {
|
||||
if (myindex == temp.size())
|
||||
myindex = 0;
|
||||
//每个元素每次循环打印个数
|
||||
for (int m = 0; m < itemLoopNum; m++) {
|
||||
myresult[index] = (myresult[index] == null ? "" : myresult[index] + ",") + temp.get(myindex);
|
||||
index++;
|
||||
}
|
||||
myindex++;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
List<String> asList = Arrays.asList(myresult);
|
||||
List<List<String>> resList = new ArrayList<>();
|
||||
for (String str : asList) {
|
||||
resList.add(new ArrayList<>(Arrays.asList(str.split(","))));
|
||||
}
|
||||
return resList;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
String str = "黑色,白色==16G,32G,64G";
|
||||
String[] list = str.split("==");
|
||||
List<List<String>> strs = new ArrayList<>();
|
||||
for (int i = 0; i < list.length; i++) {
|
||||
strs.add(Arrays.asList(list[i].split(",")));
|
||||
}
|
||||
System.out.println(strs);
|
||||
|
||||
List<List<String>> result = descartes(strs);
|
||||
System.out.println(result);
|
||||
|
||||
}
|
||||
}
|
||||
392
comm/Kernel/src/util/DateOperate.java
Executable file
392
comm/Kernel/src/util/DateOperate.java
Executable file
@@ -0,0 +1,392 @@
|
||||
package util;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
|
||||
/*******************************************************************************
|
||||
* class name:DateOperate
|
||||
*
|
||||
* description:日期时间处理类,封装了处理日期时间的常用方法。包括获取当前时间, 按指定格式格式化时间等方法
|
||||
*
|
||||
******************************************************************************/
|
||||
public class DateOperate {
|
||||
|
||||
public static final String DEFAULTSTYLE = "yyyy-MM-dd";//默认时间格式
|
||||
|
||||
public static final String DATE_TIME_STYLE_All="yyyy-MM-dd HH:mm:ss";//时间格式(全)
|
||||
|
||||
/***************************************************************************
|
||||
* 函数功能:获取当前年份
|
||||
*
|
||||
* 参数说明:无
|
||||
*
|
||||
* 返回值:返回当前年份字符串
|
||||
**************************************************************************/
|
||||
public static String getNowYear() {
|
||||
Calendar cd = Calendar.getInstance();
|
||||
int year = cd.get(Calendar.YEAR);
|
||||
return Integer.toString(year);
|
||||
}
|
||||
|
||||
/***************************************************************************
|
||||
* 函数功能:获取当前月份
|
||||
*
|
||||
* 参数说明:无
|
||||
*
|
||||
* 返回值:返回当前月份字符串
|
||||
**************************************************************************/
|
||||
public static String getNowMonth() {
|
||||
Calendar cd = Calendar.getInstance();
|
||||
int month = cd.get(Calendar.MONTH) + 1;
|
||||
if (month < 10)
|
||||
return "0" + Integer.toString(month);
|
||||
else
|
||||
return Integer.toString(month);
|
||||
}
|
||||
|
||||
/***************************************************************************
|
||||
* 函数功能:获取当前日期号
|
||||
*
|
||||
* 参数说明:无
|
||||
*
|
||||
* 返回值:返回当前日期号字符串
|
||||
**************************************************************************/
|
||||
public static String getNowDay() {
|
||||
Calendar cd = Calendar.getInstance();
|
||||
int day = cd.get(Calendar.DAY_OF_MONTH);
|
||||
if (day < 10)
|
||||
return "0" + Integer.toString(day);
|
||||
else
|
||||
return Integer.toString(day);
|
||||
}
|
||||
|
||||
/***************************************************************************
|
||||
* 函数功能:获取当前小时
|
||||
*
|
||||
* 参数说明:无
|
||||
*
|
||||
* 返回值:返回当前小时字符串
|
||||
**************************************************************************/
|
||||
public static String getNowHour() {
|
||||
Calendar cd = Calendar.getInstance();
|
||||
int hour = cd.get(Calendar.HOUR_OF_DAY);
|
||||
return Integer.toString(hour);
|
||||
}
|
||||
|
||||
/***************************************************************************
|
||||
* 函数功能:获取当前分钟
|
||||
*
|
||||
* 参数说明:无
|
||||
*
|
||||
* 返回值:返回当前分钟字符串
|
||||
**************************************************************************/
|
||||
public static String getNowMinute() {
|
||||
Calendar cd = Calendar.getInstance();
|
||||
int minute = cd.get(Calendar.MINUTE);
|
||||
return Integer.toString(minute);
|
||||
}
|
||||
|
||||
/***************************************************************************
|
||||
* 函数功能:获取当前秒钟
|
||||
*
|
||||
* 参数说明:无
|
||||
*
|
||||
* 返回值:返回当前秒钟字符串
|
||||
**************************************************************************/
|
||||
public static String getNowSecond() {
|
||||
Calendar cd = Calendar.getInstance();
|
||||
int second = cd.get(Calendar.SECOND);
|
||||
return Integer.toString(second);
|
||||
}
|
||||
|
||||
/***************************************************************************
|
||||
* 函数功能:按照指定的时间格式,格式化时间字符串
|
||||
*
|
||||
* 参数说明:
|
||||
*
|
||||
* @dateString:时间字符串
|
||||
* @formatStyle:指定的时间格式
|
||||
*
|
||||
* 返回值:返回被格式化后的日期 /
|
||||
**************************************************************************/
|
||||
public static Date formatStringToDate(String dateString, String formatStyle) {
|
||||
Date date = null;
|
||||
if (formatStyle == null || formatStyle.equals("") == true)// 如果没有指定格式,则使用默认格式
|
||||
formatStyle = DEFAULTSTYLE;
|
||||
|
||||
try {
|
||||
if(dateString==null || dateString.trim().equals(""))
|
||||
return null;
|
||||
return new SimpleDateFormat(formatStyle).parse(dateString);
|
||||
} catch (ParseException e) {
|
||||
date = null;
|
||||
e.printStackTrace();
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
/***************************************************************************
|
||||
* 函数功能:按照指定的格式获取当前时间。
|
||||
*
|
||||
* 参数说明:
|
||||
*
|
||||
* @formatStyle:指定的时间格式
|
||||
*
|
||||
* 返回值:返回指定格式的当前日期
|
||||
**************************************************************************/
|
||||
public static String getNowDate(String formatStyle)
|
||||
{
|
||||
if(formatStyle==null || formatStyle.equals(""))
|
||||
formatStyle=DEFAULTSTYLE;
|
||||
Date now = new Date();
|
||||
SimpleDateFormat formater = new SimpleDateFormat(formatStyle);
|
||||
return formater.format(now);
|
||||
}
|
||||
|
||||
public static String getNowDateTime()
|
||||
{
|
||||
Date now = new Date();
|
||||
SimpleDateFormat formater = new SimpleDateFormat(DATE_TIME_STYLE_All);
|
||||
return formater.format(now);
|
||||
}
|
||||
|
||||
public static String getNowDate()
|
||||
{
|
||||
Date now = new Date();
|
||||
SimpleDateFormat formater = new SimpleDateFormat(DEFAULTSTYLE);
|
||||
return formater.format(now);
|
||||
}
|
||||
|
||||
/***************************************************************************
|
||||
* 函数功能:比较时间迟早
|
||||
*
|
||||
* 参数说明:
|
||||
*
|
||||
* @date1:时间对象1
|
||||
*
|
||||
* @date2:时间对象2
|
||||
*
|
||||
* 返回值:如果时间对象1在时间对象2之后则返回true; 否则如果两个时间相等或时间对象1在时间对象2之前返回false;异常也返回false;
|
||||
**************************************************************************/
|
||||
public static boolean compareDate(Date date1, Date date2) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
if (date1.after(date2) == true)// 如果时间对象1在时间对象2之后
|
||||
flag = true;
|
||||
else
|
||||
flag = false;
|
||||
} catch (Exception ex) {
|
||||
flag = false;
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
// 获取某一时间段内的双休日天数
|
||||
public static int getWeekendDays(String beginDate, String endDate) {
|
||||
int count = 0;
|
||||
Date begin = formatStringToDate(beginDate, DEFAULTSTYLE);// 将起始时间字符串转换成Date类型
|
||||
Date end = formatStringToDate(endDate, DEFAULTSTYLE);// 将结束时间字符串转换成Date类型
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(begin);// 设置从起始时间开始计算
|
||||
while (true) {
|
||||
Date tempDate = calendar.getTime();// 获取当前参与判断的时间
|
||||
if (tempDate.after(end))// 如果在结束时间之后,则退出
|
||||
break;
|
||||
else
|
||||
{
|
||||
// 如果是周6或者周日
|
||||
if((calendar.get(Calendar.DAY_OF_WEEK) == 7) || (calendar.get(Calendar.DAY_OF_WEEK) == 1))
|
||||
count++;// 计数器递增
|
||||
calendar.add(Calendar.DATE, 1); // 日期递增
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
|
||||
//将日期字符串转换成Calendar对象
|
||||
public static Calendar convertDateStringToCalendar(String dateString)
|
||||
{
|
||||
Date date = formatStringToDate(dateString, DEFAULTSTYLE);// 将起始时间字符串转换成Date类型
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
return calendar;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将日期字符串转换成Calendar对象
|
||||
* @param dateString 时间字符串
|
||||
* @param timeStyle 格式
|
||||
* @return
|
||||
* @date 2008-12-30
|
||||
* @author huangzr
|
||||
*/
|
||||
public static Calendar convertDateStringToCalendar(String dateString,String timeStyle)
|
||||
{
|
||||
if (null != dateString && !"".equals(dateString)){
|
||||
if (null == timeStyle || "".equals(timeStyle.trim())) {
|
||||
timeStyle = DEFAULTSTYLE;
|
||||
}
|
||||
Date date = formatStringToDate(dateString, timeStyle);// 将起始时间字符串转换成Date类型
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
return calendar;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前日期所在的星期中的第一天(星期一)的日期
|
||||
*@param:dateString 日期字符串
|
||||
*@return:返回当前日期所在的星期中的第一天的日期
|
||||
*@throws:
|
||||
*/
|
||||
public static String getFirstDayOfWeek(String dateString)
|
||||
{
|
||||
int nowweek=DateOperate.getDayOfWeek(dateString);//获取日期的是星期几
|
||||
int distance=1-nowweek;//获取与周一相差的天数
|
||||
String firstDayOfWeek=DateOperate.getAnyDate(dateString, distance);
|
||||
return firstDayOfWeek;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取当前日期所在的星期中的最后一天(星期天)的日期
|
||||
*@param:dateString 日期字符串
|
||||
*@return:返回当前日期所在的星期中的最后一天的日期
|
||||
*@throws:
|
||||
*/
|
||||
public static String getLastDayOfWeek(String dateString)
|
||||
{
|
||||
int nowweek=DateOperate.getDayOfWeek(dateString);//获取日期的是星期几
|
||||
int distance=7-nowweek;//获取与周末相差的天数
|
||||
String lastDayOfWeek=DateOperate.getAnyDate(dateString, distance);
|
||||
return lastDayOfWeek;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 获取指定年指定月的最后一天号数(支持闰月)
|
||||
*@param:year 年
|
||||
*@param:month 月
|
||||
*@return:返回最后一天号数
|
||||
*@throws:
|
||||
*/
|
||||
public static String getLastDayOfMonth(String year,String month)
|
||||
{
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.set(Calendar.YEAR, Integer.parseInt(year));
|
||||
c.set(Calendar.MONTH,Integer.parseInt(month)-1);
|
||||
int day=c.getActualMaximum(Calendar.DAY_OF_MONTH);
|
||||
return Integer.toString(day);
|
||||
}
|
||||
|
||||
|
||||
|
||||
//获取指定的日期星期数
|
||||
public static int getDayOfWeek(String dateString)
|
||||
{
|
||||
Calendar calendar=convertDateStringToCalendar(dateString);
|
||||
int week=calendar.get(Calendar.DAY_OF_WEEK);
|
||||
if(week==1) //如果是周日,则返回7;
|
||||
week=7;
|
||||
else
|
||||
--week;//减1是因为,第一天是从周日开始算的
|
||||
return week;
|
||||
}
|
||||
|
||||
|
||||
//获取与当前日期相距任意天数的日期
|
||||
public static String getAnyDate(String nowDate, int days)
|
||||
{
|
||||
Calendar calendar = convertDateStringToCalendar(nowDate);
|
||||
calendar.add(Calendar.DATE, days);
|
||||
Date nextDate= calendar.getTime();
|
||||
return formatDateToString(nextDate,DEFAULTSTYLE);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//将日期格式化成指定格式的字符串
|
||||
public static String formatDateToString(Date date,String formatStyle)
|
||||
{
|
||||
if (formatStyle == null || formatStyle.equals("") == true)// 如果没有指定格式,则使用默认格式
|
||||
formatStyle = DEFAULTSTYLE;
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(formatStyle);
|
||||
return formatter.format(date);
|
||||
}
|
||||
|
||||
// 获取两个日期之间的天数差
|
||||
public static long getApartDate(String startDate, String endDate) {
|
||||
long result=0;
|
||||
try {
|
||||
Date begin = formatStringToDate(startDate, DEFAULTSTYLE);
|
||||
Date end = formatStringToDate(endDate, DEFAULTSTYLE);
|
||||
long l = end.getTime()-begin.getTime();
|
||||
result = l / (24 * 60 * 60 * 1000);
|
||||
|
||||
} catch (Exception ex) {
|
||||
result=-1;
|
||||
ex.printStackTrace();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Date dateAdd(Date date, long day){
|
||||
long result = (long)day * 24 * 60 * 60 * 1000;
|
||||
long d = date.getTime()+result;
|
||||
return new Date(d);
|
||||
}
|
||||
|
||||
//获取指定月份的上一个月份
|
||||
public static String getFrontMonth(int month)
|
||||
{
|
||||
int frontMonth=0;
|
||||
|
||||
if(month>12 || month<1)//如果传入的月份是不合法的
|
||||
frontMonth=-1;
|
||||
else
|
||||
{
|
||||
if(month==1)//如果传入的月份是一月份
|
||||
frontMonth=12;//则上一个月就是12月了
|
||||
else//否则,上一个月就是当前月减1
|
||||
frontMonth=--month;
|
||||
}
|
||||
if (frontMonth < 10)
|
||||
return "0" + Integer.toString(frontMonth);
|
||||
else
|
||||
return Integer.toString(frontMonth);
|
||||
}
|
||||
|
||||
public static String format(long ms) {//将毫秒数换算成x天x时x分x秒x毫秒
|
||||
int ss = 1000;
|
||||
int mi = ss * 60;
|
||||
int hh = mi * 60;
|
||||
int dd = hh * 24;
|
||||
|
||||
long day = ms / dd;
|
||||
long hour = (ms - day * dd) / hh;
|
||||
long minute = (ms - day * dd - hour * hh) / mi;
|
||||
long second = (ms - day * dd - hour * hh - minute * mi) / ss;
|
||||
long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
|
||||
|
||||
String strDay = day==0?"":day+"";
|
||||
String strHour = hour < 10 ? "0" + hour : "" + hour;
|
||||
String strMinute = minute < 10 ? "0" + minute : "" + minute;
|
||||
String strSecond = second < 10 ? "0" + second : "" + second;
|
||||
String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;
|
||||
strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : "" + strMilliSecond;
|
||||
return (strDay.equals("")?"":strDay + "天") + strHour + "小时" + strMinute + "分" + strSecond + "秒";
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(DateOperate.format(512000));
|
||||
}
|
||||
}
|
||||
812
comm/Kernel/src/util/DateUtil.java
Executable file
812
comm/Kernel/src/util/DateUtil.java
Executable file
@@ -0,0 +1,812 @@
|
||||
package util;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
|
||||
|
||||
public abstract class DateUtil {
|
||||
|
||||
public static final String DATE_FORMAT_FULL = "yyyy-MM-dd HH:mm:ss.SSS";
|
||||
public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
|
||||
/**
|
||||
* 根据传入的模式参数返回当天的日期
|
||||
* @param pattern 传入的模式
|
||||
* @return 按传入的模式返回一个字符串
|
||||
*/
|
||||
public static String getToday ( String pattern )
|
||||
{
|
||||
Date date = new Date () ;
|
||||
SimpleDateFormat sdf = new SimpleDateFormat ( pattern ) ;
|
||||
return sdf.format ( date ) ;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个日期大小
|
||||
* @param date1 日期字符串
|
||||
* @param pattern1 日期格式
|
||||
* @param date2 日期字符串
|
||||
* @param pattern2 日期格式
|
||||
* @return boolean 若是date1比date2小则返回true
|
||||
* @throws ParseException
|
||||
*/
|
||||
public static boolean compareMinDate ( String date1 , String pattern1 ,
|
||||
String date2 , String pattern2 )
|
||||
throws ParseException
|
||||
{
|
||||
Date d1 = convertToCalendar ( date1 , pattern1 ).getTime () ;
|
||||
Date d2 = convertToCalendar ( date2 , pattern2 ).getTime () ;
|
||||
return d1.before ( d2 ) ;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较两个日期大小
|
||||
* @param date1 Date
|
||||
* @param date2 Date
|
||||
* @return boolean 若是date1比date2小则返回true
|
||||
*/
|
||||
public static boolean compareMinDate ( Date date1 , Date date2 )
|
||||
{
|
||||
try
|
||||
{
|
||||
return DateUtil.compareMinDate ( DateUtil.formatDate ( date1 , "yyyy-MM-dd HH:mm:ss" ) ,
|
||||
"yyyy-MM-dd HH:mm:ss" ,
|
||||
DateUtil.formatDate ( date2 , "yyyy-MM-dd HH:mm:ss" ) ,
|
||||
"yyyy-MM-dd HH:mm:ss" ) ;
|
||||
}
|
||||
catch ( Exception ex )
|
||||
{
|
||||
return false ;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 比较两个日期大小
|
||||
* @param date1 Date
|
||||
* @param date2 Date
|
||||
* @return boolean 若是date1比date2小则返回true
|
||||
*/
|
||||
public static boolean compareMinDateForDay ( Date date1 , Date date2 )
|
||||
{
|
||||
try
|
||||
{
|
||||
return DateUtil.compareMinDate ( DateUtil.formatDate ( date1 , "yyyy-MM-dd" ) ,
|
||||
"yyyy-MM-dd" ,
|
||||
DateUtil.formatDate ( date2 , "yyyy-MM-dd" ) ,
|
||||
"yyyy-MM-dd" ) ;
|
||||
}
|
||||
catch ( Exception ex )
|
||||
{
|
||||
return false ;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据传入的日期字符串以及格式,产生一个Calendar对象
|
||||
* @param date 日期字符串
|
||||
* @param pattern 日期格式
|
||||
* @return Calendar
|
||||
* @throws ParseException 当格式与日期字符串不匹配时抛出该异常
|
||||
*/
|
||||
public static Calendar convertToCalendar ( String date , String pattern )
|
||||
throws ParseException
|
||||
{
|
||||
SimpleDateFormat sdf = new SimpleDateFormat ( pattern ) ;
|
||||
Date d = sdf.parse ( date ) ;
|
||||
GregorianCalendar calendar = new GregorianCalendar () ;
|
||||
calendar.setTime ( d ) ;
|
||||
return calendar ;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用途:以指定的格式格式化日期字符串
|
||||
* @param pattern 字符串的格式
|
||||
* @param currentDate 被格式化日期
|
||||
* @return String 已格式化的日期字符串
|
||||
* @throws NullPointerException 如果参数为空
|
||||
*/
|
||||
public static String formatDate ( Calendar currentDate , String pattern )
|
||||
{
|
||||
|
||||
Date date = currentDate.getTime () ;
|
||||
return formatDate ( date , pattern ) ;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用途:以指定的格式格式化日期字符串
|
||||
* @param pattern 字符串的格式
|
||||
* @param currentDate 被格式化日期
|
||||
* @return String 已格式化的日期字符串
|
||||
* @throws NullPointerException 如果参数为空
|
||||
*/
|
||||
public static String formatDate ( Date currentDate , String pattern ) {
|
||||
|
||||
SimpleDateFormat sdf = new SimpleDateFormat ( pattern ) ;
|
||||
return sdf.format ( currentDate ) ;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用途:以指定的格式格式化日期字符串
|
||||
* @param currentDate 被格式化日期字符串 必须为yyyymmdd
|
||||
* @param pattern 字符串的格式
|
||||
* @return String 已格式化的日期字符串
|
||||
* @throws NullPointerException 如果参数为空
|
||||
* @throws java.text.ParseException 若被格式化日期字符串不是yyyymmdd形式时抛出
|
||||
*/
|
||||
public static String formatDate ( String currentDate , String pattern )
|
||||
throws java.text.ParseException
|
||||
{
|
||||
|
||||
SimpleDateFormat sdf = new SimpleDateFormat ( "yyyyMMdd" ) ;
|
||||
Date date = sdf.parse ( currentDate ) ;
|
||||
sdf.applyPattern ( pattern ) ;
|
||||
return sdf.format ( date ) ;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用途:以指定的格式格式化日期字符串
|
||||
* @param strDate 被格式化日期字符串 必须为yyyymmdd
|
||||
* @param formator 格式字符串
|
||||
* @return String 已格式化的日期字符串
|
||||
* @throws NullPointerException 如果参数为空
|
||||
* @throws java.text.ParseException 若被格式化日期字符串不是yyyymmdd形式时抛出
|
||||
*/
|
||||
public static Calendar strToDate ( String strDate , String formator )
|
||||
{
|
||||
|
||||
|
||||
Calendar date = Calendar.getInstance () ;
|
||||
date.setTime ( java.sql.Date.valueOf ( strDate ) ) ;
|
||||
return date ;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前时间是否在参数时间内(当开始时间大于结束时间表示时间段的划分从begin到第二天的end时刻)
|
||||
* 例如当前时间在12:00 传入参数为(12,12,0,1)返回true
|
||||
* 例如当前时间在12:00 传入参数为(12,12,1,0)返回true
|
||||
* @param beginHour int 开始的小时值
|
||||
* @param endHour int 结束的小时值
|
||||
* @param beginMinu int 开始的分钟值
|
||||
* @param endMinu int 结束的分钟值
|
||||
* @return boolean
|
||||
*/
|
||||
public static boolean isInTime ( int beginHour , int endHour ,
|
||||
int beginMinu ,
|
||||
int endMinu )
|
||||
{
|
||||
Date date1 = new Date () ;
|
||||
Date date2 = new Date () ;
|
||||
Date nowDate = new Date () ;
|
||||
date1.setHours ( beginHour ) ;
|
||||
date2.setHours ( endHour ) ;
|
||||
date1.setMinutes ( beginMinu ) ;
|
||||
date2.setMinutes ( endMinu ) ;
|
||||
if ( date1 == date2 )
|
||||
{
|
||||
return false ;
|
||||
}
|
||||
//yyyy-MM-dd HH:mm:ss
|
||||
if (
|
||||
DateUtil.compare ( date2 , date1 ) )
|
||||
{
|
||||
if ( !DateUtil.compare ( nowDate , date1 )
|
||||
|| DateUtil.compare ( nowDate , date2 ) )
|
||||
{
|
||||
return true ;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (
|
||||
!DateUtil.compare ( nowDate , date1 ) &&
|
||||
DateUtil.compare ( nowDate , date2 )
|
||||
)
|
||||
{
|
||||
return true ;
|
||||
}
|
||||
}
|
||||
return false ;
|
||||
}
|
||||
|
||||
/**
|
||||
* 开始时间小于结束时间返回true,否则返回false
|
||||
* @param beginDate Date
|
||||
* @param endDate Date
|
||||
* @return boolean
|
||||
*/
|
||||
public static boolean compare ( Date beginDate , Date endDate )
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
return DateUtil.compareMinDate ( DateUtil.formatDate ( beginDate ,
|
||||
"yyyy-MM-dd HH:mm:ss" ) ,
|
||||
"yyyy-MM-dd HH:mm:ss" ,
|
||||
DateUtil.formatDate ( endDate ,
|
||||
"yyyy-MM-dd HH:mm:ss" ) ,
|
||||
"yyyy-MM-dd HH:mm:ss" ) ;
|
||||
|
||||
}
|
||||
catch ( Exception ex )
|
||||
{
|
||||
// log.error ( "时间格式转换错误" + ex ) ;
|
||||
return false ;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将指定格式的时间String转为Date类型
|
||||
* @param dateStr String 待转换的时间String
|
||||
* @param pattern String 转换的类型
|
||||
* @throws ParseException
|
||||
* @return Date
|
||||
*/
|
||||
public static Date convertStringToDate ( String dateStr , String pattern )
|
||||
|
||||
{
|
||||
try{
|
||||
if ( Strings.isEmpty(dateStr))
|
||||
{
|
||||
return null ;
|
||||
}
|
||||
SimpleDateFormat sdf = new SimpleDateFormat ( pattern ) ;
|
||||
return sdf.parse ( dateStr ) ;
|
||||
} catch (ParseException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
return new Date();
|
||||
|
||||
}
|
||||
|
||||
public static String convertDateToString ( Date date ) throws ParseException {
|
||||
if (date == null) {
|
||||
return "";
|
||||
}
|
||||
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取比当前日期早多少天或者晚多少天的日期 例如 前五天 -5 后五天 5
|
||||
* @param days
|
||||
* @param format 返回日期的格式
|
||||
* @return 格式化好的字符串
|
||||
*/
|
||||
|
||||
public static String DateBefAft(int days,String format){
|
||||
//
|
||||
if(format==null || "".equals(format))
|
||||
format="yyyy-MM-dd";
|
||||
Calendar now = Calendar.getInstance();
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(format);
|
||||
now.add(Calendar.DAY_OF_YEAR,-days);
|
||||
return formatter.format(now.getTime());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取比当前日期早多少天或者晚多少天的日期 例如 前五天 -5 后五天 5
|
||||
* @param days
|
||||
* @param format 返回日期的格式
|
||||
* @return 日期
|
||||
* @throws ParseException
|
||||
*/
|
||||
|
||||
public static Date DateBefAft_returnDate(int days,String format) throws ParseException{
|
||||
//
|
||||
if(format==null || "".equals(format))
|
||||
format="yyyy-MM-dd";
|
||||
Calendar now = Calendar.getInstance();
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(format);
|
||||
now.add(Calendar.DAY_OF_YEAR,-days);
|
||||
return convertStringToDate(formatter.format(now.getTime()),"yyyy-MM-dd");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取比当前日期早多少小时或者晚多少小时 例如 前五小时 -5 后五小时 5
|
||||
* @param days
|
||||
* @param format 返回日期的格式
|
||||
* @return 日期
|
||||
* @throws ParseException
|
||||
*/
|
||||
|
||||
public static Date HourBefAft_returnDate(int hours) throws ParseException{
|
||||
|
||||
Calendar now = Calendar.getInstance();
|
||||
now.add(Calendar.HOUR_OF_DAY,-hours);
|
||||
return now.getTime();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 格式化 Date 类型的日期
|
||||
* @param date 传入日期
|
||||
* @param format 设定日期的显示格式 默认 2006-12-25
|
||||
* @return 格式化后的日期
|
||||
*/
|
||||
public static String DatetoString(Date date,String format){
|
||||
if(format==null || "".equals(format))
|
||||
format="yyyy-MM-dd";
|
||||
SimpleDateFormat formatter = new SimpleDateFormat(format);
|
||||
return formatter.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化 LocalDateTime 类型的日期
|
||||
* @param format 设定日期的显示格式 默认 2006-12-25
|
||||
* @param date 传入日期
|
||||
* @param s
|
||||
* @return 格式化后的日期
|
||||
*/
|
||||
public static String LocalDateToString(LocalDateTime date){
|
||||
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
return dateTimeFormatter.format(date);
|
||||
}
|
||||
|
||||
public static void shortDateToLongDate(String strDate) {
|
||||
|
||||
}
|
||||
/**
|
||||
* 获取某时间的中文星期(如:星期一、星期二),每星期的第一天是星期日
|
||||
* @param date:日期
|
||||
* @return
|
||||
*/
|
||||
public static String getWeekCS(Date date)
|
||||
{
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
String[] week = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
|
||||
return week[calendar.get(Calendar.DAY_OF_WEEK) - 1];
|
||||
}
|
||||
/**
|
||||
* 获取某时间的星期
|
||||
* @param date:日期
|
||||
* @return
|
||||
*/
|
||||
public static int getWeek(Date date)
|
||||
{
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
|
||||
return calendar.get(Calendar.DAY_OF_WEEK)-1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时间的中文星期(如:星期一、星期二),每星期的第一天是星期日
|
||||
* @return
|
||||
*/
|
||||
public static String getWeekCSToday()
|
||||
{
|
||||
return getWeekCS(new Date());
|
||||
}
|
||||
|
||||
/**
|
||||
* 用当前日期作为文件名,一般不会重名取到的值是从当前时间的字符串格式,带有微秒,建议作为记录id
|
||||
* @return
|
||||
*/
|
||||
public static String getTimeStamp(String strFormat)
|
||||
{
|
||||
Date currentTime = new Date();
|
||||
return dateToString(currentTime, strFormat);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用当前日期作为文件名,一般不会重名取到的值是从1970年1月1日00:00:00开始算起所经过的微秒数
|
||||
* @return
|
||||
*/
|
||||
public static String getFileName()
|
||||
{
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
String filename = String.valueOf(calendar.getTimeInMillis());
|
||||
return filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取两个日期之间所差的天数
|
||||
* @param from:开始日期
|
||||
* @param to:结束日期
|
||||
* @return:所差的天数(非负整数)
|
||||
*/
|
||||
public static int dateNum(Date from, Date to)
|
||||
{
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(from);
|
||||
calendar.set(Calendar.HOUR, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
Date fromDate = calendar.getTime();
|
||||
|
||||
calendar.setTime(to);
|
||||
calendar.set(Calendar.HOUR, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
Date toDate = calendar.getTime();
|
||||
int diff = Math.abs((int) ((fromDate.getTime() - toDate.getTime()) / (24 * 3600 * 1000)));
|
||||
return diff;
|
||||
}
|
||||
/**
|
||||
* 获取两个日期之间所差的分钟数
|
||||
* @param from:开始日期
|
||||
* @param to:结束日期
|
||||
* @return:所差的天数(非负整数)
|
||||
*/
|
||||
public static int minuteNum(Date from, Date to)
|
||||
{
|
||||
|
||||
int diff = Math.abs((int) ((from.getTime() - to.getTime()) / (60*1000)));
|
||||
return diff;
|
||||
}
|
||||
/**
|
||||
* 获取两个日期之间所差的分钟数
|
||||
* @param from:开始日期
|
||||
* @param to:结束日期
|
||||
* @return:所差的天数(非负整数)
|
||||
*/
|
||||
public static int secondNum(Date from, Date to)
|
||||
{
|
||||
|
||||
int diff = Math.abs((int) ((from.getTime() - to.getTime()) / (1000)));
|
||||
return diff;
|
||||
}
|
||||
/**
|
||||
* 获取两个日期之间所差的周数
|
||||
* @param from
|
||||
* @param to
|
||||
* @return
|
||||
*/
|
||||
public static int weekNum(Date from, Date to)
|
||||
{
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取date前或后nDay天的日期
|
||||
* @param date:开始日期
|
||||
* @param nDay:天数
|
||||
* @param type:正为后nDay天的日期,否则为前nDay天的日期。
|
||||
* @return
|
||||
*/
|
||||
private static Date getDate(Date date, int nDay, int type,String format)
|
||||
{
|
||||
long millisecond = date.getTime(); //从1970年1月1日00:00:00开始算起所经过的微秒数
|
||||
long msel = nDay * 24 * 3600 * 1000l; //获取nDay天总的毫秒数
|
||||
millisecond = millisecond + ((type > 0) ? msel : (-msel));
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTimeInMillis(millisecond);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取n天后的日期
|
||||
* @param date
|
||||
* @param nDay
|
||||
* @return
|
||||
*/
|
||||
public static Date dateAfterNDate(Date date, int nDay,String format)
|
||||
{
|
||||
return getDate(date, nDay, 1,format);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取n天后的日期
|
||||
* @param strDate
|
||||
* @param nDay
|
||||
* @return
|
||||
*/
|
||||
public static Date dateAfterNDate(String strDate, int nDay,String format)
|
||||
{
|
||||
Date date = stringToDate(strDate, format);
|
||||
return dateAfterNDate(date, nDay,format);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取n天前的日期
|
||||
* @param date
|
||||
* @param nDay
|
||||
* @return
|
||||
*/
|
||||
public static Date dateBeforeNDate(Date date, int nDay,String format)
|
||||
{
|
||||
return getDate(date, nDay, -1,format);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取n天前的日期
|
||||
* @param strDate
|
||||
* @param nDay
|
||||
* @return
|
||||
*/
|
||||
public static Date dateBeforeNDate(String strDate, int nDay,String format)
|
||||
{
|
||||
Date date = stringToDate(strDate, format);
|
||||
return dateBeforeNDate(date, nDay,format);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将日期转化为字符串的形式
|
||||
* @param date
|
||||
* @param strFormat
|
||||
* @return
|
||||
*/
|
||||
public static String dateToString(Date date, String strFormat)
|
||||
{
|
||||
if(date==null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
if(strFormat == null)
|
||||
{
|
||||
strFormat = "yyyy-MM-dd";
|
||||
}
|
||||
SimpleDateFormat format = new SimpleDateFormat(strFormat);
|
||||
return format.format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将字符串转化为Date类型。如果该字符串无法转化为Date类型的数据,则返回null。
|
||||
* @param strDate
|
||||
* @param strFormat
|
||||
* strDate和strFormat的格式要一样。即如果strDate="20061112",则strFormat="yyyyMMdd"
|
||||
* @return
|
||||
*/
|
||||
public static Date stringToDate(String strDate, String strFormat)
|
||||
{
|
||||
Date date = null;
|
||||
try
|
||||
{
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(strFormat);
|
||||
date = sdf.parse(strDate);
|
||||
if (!sdf.format(date).equals(strDate))
|
||||
{
|
||||
date = null;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
date = null;
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取n月之前或之后的日期
|
||||
* @param date
|
||||
* @param nMonth
|
||||
* @param type(只能为-1或1)
|
||||
* @return
|
||||
*/
|
||||
public static Date getDateMonth(Date date, int nMonth, int type)
|
||||
{
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
int nYear = nMonth / 12;
|
||||
int month = nMonth % 12;
|
||||
calendar.add(Calendar.YEAR, nYear * type);
|
||||
Date desDate = calendar.getTime();
|
||||
calendar.add(Calendar.MONTH, month * type);
|
||||
if(type < 0)
|
||||
{
|
||||
while(!calendar.getTime().before(desDate))
|
||||
{
|
||||
calendar.add(Calendar.YEAR, type);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
while(!calendar.getTime().after(desDate))
|
||||
{
|
||||
calendar.add(Calendar.YEAR, type);
|
||||
}
|
||||
}
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时间所在的周的最后一天(周一为第一天)
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static Date getLastDateOfWeek(Date date)
|
||||
{
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
int index = calendar.get(Calendar.DAY_OF_WEEK);
|
||||
index = (index == 1) ? (index + 7) : index;
|
||||
date = DateUtil.dateAfterNDate(date, 8 - index,"yyyy-MM-dd");
|
||||
return date;
|
||||
}
|
||||
/**
|
||||
* 获取当前时间所在的周的第一天(周一为第一天)
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static Date getFirstDateOfWeek(Date date)
|
||||
{
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
int index = calendar.get(Calendar.DAY_OF_WEEK);
|
||||
index = (index == 1) ? (index + 7) : index;
|
||||
date = DateUtil.dateBeforeNDate(date, index - 2,"yyyy-MM-dd");
|
||||
return date;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取date所在的月份的最后一天
|
||||
* 方法是获取下个月的第一天,然后获取前一天的日期
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static Date getLastDateOfMonth(Date date)
|
||||
{
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.set(Calendar.DATE, 1);
|
||||
date = calendar.getTime();
|
||||
date = DateUtil.getDateMonth(date, 1, 1);
|
||||
date = DateUtil.dateBeforeNDate(date, 1,"yyyy-MM-dd");
|
||||
return date;
|
||||
}
|
||||
|
||||
public static Date getFirstDateOfMonth(Date date)
|
||||
{
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.set(Calendar.DATE, 1);
|
||||
return calendar.getTime();
|
||||
}
|
||||
/**
|
||||
* 获取季度的最后一天
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static Date getLastDateOfSeason(Date date)
|
||||
{
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
int index = calendar.get(Calendar.MONTH);
|
||||
index = index / 3;
|
||||
Date[] dates = new Date[4];
|
||||
calendar.set(calendar.get(Calendar.YEAR), 2, 31);
|
||||
dates[0] = calendar.getTime();
|
||||
calendar.set(calendar.get(Calendar.YEAR), 5, 30);
|
||||
dates[1] = calendar.getTime();
|
||||
calendar.set(calendar.get(Calendar.YEAR), 8, 30);
|
||||
dates[2] = calendar.getTime();
|
||||
calendar.set(calendar.get(Calendar.YEAR), 11, 31);
|
||||
dates[3] = calendar.getTime();
|
||||
return dates[index];
|
||||
}
|
||||
/**
|
||||
* 创建日期date
|
||||
* @param year:年
|
||||
* @param month:月
|
||||
* @param day:日
|
||||
* @return
|
||||
*/
|
||||
public static Date createDate(int year, int month, int day)
|
||||
{
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.set(year, month, day);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
/**获取N个月后日期
|
||||
* @param date
|
||||
* @param n
|
||||
* @return
|
||||
*/
|
||||
public static Date getDateAfterMonths(Date date,int n){
|
||||
|
||||
GregorianCalendar grc=new GregorianCalendar();
|
||||
grc.setTime(date);
|
||||
grc.add(GregorianCalendar.MONTH,n);
|
||||
return grc.getTime();
|
||||
}
|
||||
/**
|
||||
* 返回excel cell在java中日期值
|
||||
* @param DateNumber 日期cell 的值
|
||||
* @return
|
||||
*/
|
||||
public static Date getExcelDateNumberToDate(int DateNumber){
|
||||
//发现excel单元格的日期值1900-1-1值为2 java的月份是0-11表示 故初始值设置如下
|
||||
Calendar calendar = new GregorianCalendar(1900,0,-1);
|
||||
calendar.add(calendar.DATE,DateNumber);
|
||||
return calendar.getTime();
|
||||
}
|
||||
/**
|
||||
* 计算个时间的相差数
|
||||
* @param diff
|
||||
* @return
|
||||
*/
|
||||
public static String getTimes(Date beginDate,Date endDate){
|
||||
Long diff=endDate.getTime()-beginDate.getTime();
|
||||
Long day = diff / (24 * 60 * 60 * 1000);
|
||||
Long hour = (diff / (60 * 60 * 1000) - day * 24);
|
||||
Long min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
|
||||
|
||||
return (day>0?day+"天":"")+(hour>0?hour+"小时":"")+min+"分钟";
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 将日期变为当天最小时间,例如2015-08-15 09:32:18改为2015-08-15 00:00:00
|
||||
*
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static Date minDate(Date date) {
|
||||
if (null == date) {
|
||||
return null;
|
||||
} else {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 0);
|
||||
calendar.set(Calendar.MINUTE, 0);
|
||||
calendar.set(Calendar.SECOND, 0);
|
||||
calendar.set(Calendar.MILLISECOND, 000);
|
||||
|
||||
date = calendar.getTime();
|
||||
return date;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将日期变为当天最大时间,例如2015-08-15 09:32:18改为2015-08-15 23:59:59
|
||||
*
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static Date maxDate(Date date) {
|
||||
if (null == date) {
|
||||
return null;
|
||||
} else {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setTime(date);
|
||||
calendar.set(Calendar.HOUR_OF_DAY, 23);
|
||||
calendar.set(Calendar.MINUTE, 59);
|
||||
calendar.set(Calendar.SECOND, 59);
|
||||
calendar.set(Calendar.MILLISECOND, 999);
|
||||
|
||||
date = calendar.getTime();
|
||||
return date;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取比当前日期早多少分钟或者晚多少分钟 例如 前五分钟 -5 后五分钟 5
|
||||
* @param format 返回日期的格式
|
||||
* @return 日期
|
||||
* @throws ParseException
|
||||
*/
|
||||
|
||||
public static Date MinuteBefAft_returnDate(int minute) throws ParseException{
|
||||
|
||||
Calendar now = Calendar.getInstance();
|
||||
now.add(Calendar.MINUTE,-minute);
|
||||
return now.getTime();
|
||||
}
|
||||
|
||||
public static void main(String[] args){
|
||||
Date current=new Date();
|
||||
current.setDate(current.getDate()+2);
|
||||
//System.out.println(dateNum(new Date(),current));
|
||||
|
||||
//System.out.println(getFirstDateOfWeek(new Date()));
|
||||
//System.out.println(getLastDateOfWeek(new Date()));
|
||||
//System.out.println(getWeek(new Date()));
|
||||
|
||||
System.out.println(DateUtil.DateBefAft(1,"yyyy-MM-dd"));
|
||||
|
||||
}
|
||||
}
|
||||
384
comm/Kernel/src/util/DateUtils.java
Executable file
384
comm/Kernel/src/util/DateUtils.java
Executable file
@@ -0,0 +1,384 @@
|
||||
package util;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.*;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import kernel.util.PropertiesUtil;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
public abstract class DateUtils {
|
||||
|
||||
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
|
||||
|
||||
public static final String DEFAULT_TIME_ZONE = PropertiesUtil.getProperty("mall.default.time.zone");
|
||||
|
||||
public static final String NORMAL_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
/**
|
||||
* 根据yyyy-MM-dd HH:mm:ss格式返回指定时间
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static final String formatOfDateTime(Date date) {
|
||||
return format(date, NORMAL_DATE_FORMAT);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据yyyy-MM-dd HH:mm:ss格式返回当前时间
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static final String formatOfDateTime() {
|
||||
return formatOfDateTime(new Date());
|
||||
}
|
||||
|
||||
public static final String format(Date date, String pattern) {
|
||||
if (date == null) {
|
||||
throw new NullPointerException("时间不能为NULL!");
|
||||
}
|
||||
|
||||
if (StringUtils.isEmpty(pattern)) {
|
||||
throw new IllegalArgumentException("格式pattern不能为空字符串!");
|
||||
}
|
||||
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
calendar.setFirstDayOfWeek(Calendar.MONDAY);
|
||||
|
||||
DateFormat formater = new SimpleDateFormat(pattern);
|
||||
formater.setCalendar(calendar);
|
||||
|
||||
return formater.format(date);
|
||||
}
|
||||
|
||||
public static Date toDate(String string) {
|
||||
return toDate(string, DEFAULT_DATE_FORMAT);
|
||||
}
|
||||
|
||||
public static Date toDate(String string, String pattern) {
|
||||
return toDate(string, pattern, TimeZone.getTimeZone(DEFAULT_TIME_ZONE));
|
||||
}
|
||||
|
||||
public static Date toDate(String string, String pattern, TimeZone timeZone) {
|
||||
try {
|
||||
SimpleDateFormat sdf = (SimpleDateFormat) createDateFormat(pattern, timeZone);
|
||||
return sdf.parse(string);
|
||||
} catch (ParseException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static String format(Date date, String pattern, TimeZone timeZone) {
|
||||
DateFormat df = createDateFormat(pattern, timeZone);
|
||||
return df.format(date);
|
||||
}
|
||||
|
||||
public static DateFormat createDateFormat(String pattern) {
|
||||
return createDateFormat(pattern, TimeZone.getTimeZone(DEFAULT_TIME_ZONE));
|
||||
}
|
||||
|
||||
public static DateFormat createDateFormat(String pattern, TimeZone timeZone) {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
|
||||
TimeZone gmt = timeZone;
|
||||
sdf.setTimeZone(gmt);
|
||||
sdf.setLenient(true);
|
||||
return sdf;
|
||||
}
|
||||
|
||||
public static int getYear(java.util.Date date) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(date);
|
||||
return calendar.get(Calendar.YEAR);
|
||||
}
|
||||
|
||||
public static String getShortYear(java.util.Date date) {
|
||||
String year = getYear(date) + "";
|
||||
int length = year.length();
|
||||
return year.substring(length - 2, length);
|
||||
}
|
||||
|
||||
public static int getMonth(java.util.Date date) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(date);
|
||||
return calendar.get(Calendar.MONTH) + 1;
|
||||
}
|
||||
|
||||
public static int getDay(java.util.Date date) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(date);
|
||||
return calendar.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
|
||||
public static int getHour(java.util.Date date) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(date);
|
||||
return calendar.get(Calendar.HOUR_OF_DAY);
|
||||
}
|
||||
|
||||
public static int getMinute(java.util.Date date) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(date);
|
||||
return calendar.get(Calendar.MINUTE);
|
||||
}
|
||||
|
||||
public static int getSecond(java.util.Date date) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(date);
|
||||
return calendar.get(Calendar.SECOND);
|
||||
}
|
||||
|
||||
public static Date addMilliSecond(java.util.Date oldDate, int addMilliSecond) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.MILLISECOND, addMilliSecond);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date addSecond(java.util.Date oldDate, int addSecond) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.SECOND, addSecond);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date addMinute(java.util.Date oldDate, int addMinutes) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.MINUTE, addMinutes);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date addHour(java.util.Date oldDate, int addHours) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.HOUR, addHours);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date addDay(java.util.Date oldDate, int addDays) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.DATE, addDays);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date addMonth(java.util.Date oldDate, int addMonths) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.MONTH, addMonths);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date addYear(java.util.Date oldDate, int addYears) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.add(Calendar.YEAR, addYears);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static long calcTimeBetween(String unitType, Date startDate, Date endDate) {
|
||||
Assert.hasText(unitType);
|
||||
Assert.notNull(startDate);
|
||||
Assert.notNull(endDate);
|
||||
long between = endDate.getTime() - startDate.getTime();
|
||||
if (unitType.equals("ms")) {
|
||||
return between;
|
||||
} else if (unitType.equals("s")) {
|
||||
return between / 1000;// 返回秒
|
||||
} else if (unitType.equals("m")) {
|
||||
return between / 60000;// 返回分钟
|
||||
} else if (unitType.equals("h")) {
|
||||
return between / 3600000;// 返回小时
|
||||
} else if (unitType.equals("d")) {
|
||||
return between / 86400000;// 返回天数
|
||||
} else {
|
||||
throw new IllegalArgumentException("the unitType is unknown");
|
||||
}
|
||||
}
|
||||
|
||||
public static long calcTimeBetweenInMillis(Date startDate, Date endDate) {
|
||||
return calcTimeBetween("ms", startDate, endDate);
|
||||
}
|
||||
|
||||
public static long calcTimeBetweenInSecond(Date startDate, Date endDate) {
|
||||
return calcTimeBetween("s", startDate, endDate);
|
||||
}
|
||||
|
||||
public static long calcTimeBetweenInMinute(Date startDate, Date endDate) {
|
||||
return calcTimeBetween("m", startDate, endDate);
|
||||
}
|
||||
|
||||
public static long calcTimeBetweenInHour(Date startDate, Date endDate) {
|
||||
return calcTimeBetween("h", startDate, endDate);
|
||||
}
|
||||
|
||||
public static long calcTimeBetweenInDay(Date startDate, Date endDate) {
|
||||
return calcTimeBetween("d", startDate, endDate);
|
||||
}
|
||||
|
||||
public static Date roundYear(Date date) {
|
||||
return org.apache.commons.lang.time.DateUtils.round(date, Calendar.YEAR);
|
||||
}
|
||||
|
||||
public static Date roundMonth(Date date) {
|
||||
return org.apache.commons.lang.time.DateUtils.round(date, Calendar.MONTH);
|
||||
}
|
||||
|
||||
public static Date roundDay(Date date) {
|
||||
return org.apache.commons.lang.time.DateUtils.round(date, Calendar.DATE);
|
||||
}
|
||||
|
||||
public static Date roundHour(Date date) {
|
||||
return org.apache.commons.lang.time.DateUtils.round(date, Calendar.HOUR);
|
||||
}
|
||||
|
||||
public static Date roundMinute(Date date) {
|
||||
return org.apache.commons.lang.time.DateUtils.round(date, Calendar.MINUTE);
|
||||
}
|
||||
|
||||
public static Date roundSecond(Date date) {
|
||||
return org.apache.commons.lang.time.DateUtils.round(date, Calendar.SECOND);
|
||||
}
|
||||
|
||||
public static Date truncateYear(Date date) {
|
||||
return org.apache.commons.lang.time.DateUtils.truncate(date, Calendar.YEAR);
|
||||
}
|
||||
|
||||
public static Date truncateMonth(Date date) {
|
||||
return org.apache.commons.lang.time.DateUtils.truncate(date, Calendar.MONTH);
|
||||
}
|
||||
|
||||
public static Date truncateDay(Date date) {
|
||||
return org.apache.commons.lang.time.DateUtils.truncate(date, Calendar.DATE);
|
||||
}
|
||||
|
||||
public static Date truncateHour(Date date) {
|
||||
return org.apache.commons.lang.time.DateUtils.truncate(date, Calendar.HOUR);
|
||||
|
||||
}
|
||||
|
||||
public static Date truncateMinute(Date date) {
|
||||
return org.apache.commons.lang.time.DateUtils.truncate(date, Calendar.MINUTE);
|
||||
}
|
||||
|
||||
public static Date truncateSecond(Date date) {
|
||||
return org.apache.commons.lang.time.DateUtils.truncate(date, Calendar.SECOND);
|
||||
}
|
||||
|
||||
public static Date setHour(Date oldDate, int newHour) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.set(Calendar.HOUR, newHour);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date setMinute(Date oldDate, int newMinute) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.set(Calendar.MINUTE, newMinute);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date setSecond(Date oldDate, int newSecond) {
|
||||
Calendar calendar = (Calendar) Calendar.getInstance().clone();
|
||||
calendar.setTime(oldDate);
|
||||
calendar.set(Calendar.SECOND, newSecond);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param dt Date
|
||||
* @return boolean
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
public static boolean isRYear(Date dt) {
|
||||
return (isRYear(1900 + dt.getYear()));
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param y int
|
||||
* @return boolean
|
||||
*/
|
||||
public static boolean isRYear(int y) {
|
||||
return (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一个日期的时间字符串
|
||||
*
|
||||
* @param dt Date
|
||||
* @return String
|
||||
*/
|
||||
public static String getTimeStr(Date dt) {
|
||||
return new SimpleDateFormat("HH:mm:ss").format(dt);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一个日期值的日期字符串
|
||||
*
|
||||
* @param dt Date
|
||||
* @return String
|
||||
*/
|
||||
public static String getDateStr(Date dt) {
|
||||
return new SimpleDateFormat("yyyy-MM-dd").format(dt);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取一个日期值的带时间日期字符串
|
||||
*
|
||||
* @param dt Date
|
||||
* @return String
|
||||
*/
|
||||
public static String getLongDate(Date dt) {
|
||||
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dt);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param dt Date
|
||||
* @return String
|
||||
*/
|
||||
public static String toString(Date dt) {
|
||||
return format(dt, "yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param date Date
|
||||
* @return Timestamp added by jiayc
|
||||
*/
|
||||
public static java.sql.Timestamp dateToTimeStamp(java.util.Date date) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
} else {
|
||||
return new java.sql.Timestamp(date.getTime());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return 获取当前时间到第二天0点0分0秒相差的秒数
|
||||
*/
|
||||
public static int getTomorrowStartSeconds() {
|
||||
long now = LocalDateTime.of(LocalDate.now(), LocalTime.now()).atZone(ZoneId.systemDefault()).toEpochSecond();
|
||||
return (int) (LocalDateTime.of(LocalDate.now(), LocalTime.MIN).plusDays(1).atZone(ZoneId.systemDefault()).toEpochSecond()-now);
|
||||
}
|
||||
|
||||
// public static void main(String[] args) {
|
||||
// DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
// String now = LocalDateTime.of(LocalDate.now(), LocalTime.now()).atZone(ZoneId.systemDefault()).format(dateTimeFormatter);
|
||||
// System.out.println("now = " + now);
|
||||
// final String zero = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).plusDays(1).atZone(ZoneId.systemDefault()).format(dateTimeFormatter);
|
||||
// System.out.println("zero = " + zero);
|
||||
// System.out.println("getTomorrowStartTime() = " + getTomorrowStartSeconds());
|
||||
// }
|
||||
|
||||
}
|
||||
150
comm/Kernel/src/util/FileUtil.java
Executable file
150
comm/Kernel/src/util/FileUtil.java
Executable file
@@ -0,0 +1,150 @@
|
||||
package util;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.jar.JarOutputStream;
|
||||
import java.util.zip.ZipEntry;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
public class FileUtil {
|
||||
|
||||
private static Logger logger = LogManager.getLogger(FileUtil.class);
|
||||
|
||||
private static final int BUFFER_SIZE = 16 * 1024;
|
||||
|
||||
public static void copy(String src, String dst) {
|
||||
File srcFile = new File(src);
|
||||
File dstFile = new File(dst);
|
||||
if(!dstFile.getParentFile().exists()){
|
||||
dstFile.getParentFile().mkdirs();
|
||||
}
|
||||
copy(srcFile, dstFile);
|
||||
}
|
||||
|
||||
public static void copy(File src, File dst) {
|
||||
try {
|
||||
InputStream in = null;
|
||||
OutputStream out = null;
|
||||
|
||||
try {
|
||||
in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
|
||||
out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
|
||||
byte[] buffer = new byte[BUFFER_SIZE];
|
||||
while (in.read(buffer) > 0) {
|
||||
out.write(buffer);
|
||||
}
|
||||
} finally {
|
||||
if (null != in) {
|
||||
in.close();
|
||||
}
|
||||
if (null != out) {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean zipFile(String zipFile) {
|
||||
return zipFile(zipFile, zipFile + ".zip", true, false);
|
||||
}
|
||||
|
||||
/***************************************************************************
|
||||
* 压缩文件
|
||||
*
|
||||
* @param backupFile
|
||||
*/
|
||||
public static boolean zipFile(String zipFile, String destFile, boolean includeChildren, boolean includeBlankDir) {
|
||||
|
||||
boolean zipFileSuccess = false;
|
||||
JarOutputStream zo = null;
|
||||
try {
|
||||
zo = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(destFile)));
|
||||
zip(zipFile, new File(zipFile), zo, includeChildren, includeBlankDir);
|
||||
|
||||
zipFileSuccess = true;
|
||||
} catch (FileNotFoundException e) {
|
||||
logger.error("压缩文件的时候,发生FileNotFoundException!", e);
|
||||
} catch (IOException e) {
|
||||
logger.error("压缩文件的时候,发生IOException!", e);
|
||||
} finally {
|
||||
if (zo != null) {
|
||||
IOUtils.closeQuietly(zo);
|
||||
}
|
||||
}
|
||||
return zipFileSuccess;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param path
|
||||
* 要压缩的路径, 可以是目录, 也可以是文件.
|
||||
* @param basePath
|
||||
* 如果path是目录,它一般为new File(path), 作用是:使输出的zip文件以此目录为根目录,
|
||||
* 如果为null它只压缩文件, 不解压目录.
|
||||
* @param zo
|
||||
* 压缩输出流
|
||||
* @param isRecursive
|
||||
* 是否递归
|
||||
* @param isOutBlankDir
|
||||
* 是否输出空目录, 要使输出空目录为true,同时baseFile不为null.
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void zip(String path, File basePath, JarOutputStream zo, boolean isRecursive, boolean isOutBlankDir)
|
||||
throws IOException {
|
||||
File inFile = new File(path);
|
||||
|
||||
File[] files = new File[0];
|
||||
// try {
|
||||
if (inFile.isDirectory()) { // 是目录
|
||||
files = inFile.listFiles();
|
||||
}
|
||||
else if (inFile.isFile()) { // 是文件
|
||||
files = new File[1];
|
||||
files[0] = inFile;
|
||||
}
|
||||
byte[] buf = new byte[1024];
|
||||
int len;
|
||||
for (int i = 0; i < files.length; i++) {
|
||||
String pathName = "";
|
||||
if (basePath != null) {
|
||||
if (basePath.isDirectory()) {
|
||||
pathName = files[i].getPath().substring(basePath.getPath().length() + 1);
|
||||
}
|
||||
else {// 文件
|
||||
pathName = files[i].getPath().substring(basePath.getParent().length() + 1);
|
||||
}
|
||||
}
|
||||
else {
|
||||
pathName = files[i].getName();
|
||||
}
|
||||
if (files[i].isDirectory()) {
|
||||
if (isOutBlankDir && basePath != null) {
|
||||
zo.putNextEntry(new ZipEntry(pathName + File.separator)); // 可以使空目录也放进去
|
||||
}
|
||||
if (isRecursive) { // 递归
|
||||
zip(files[i].getPath(), basePath, zo, isRecursive, isOutBlankDir);
|
||||
}
|
||||
}
|
||||
else {
|
||||
FileInputStream fin = new FileInputStream(files[i]);
|
||||
zo.putNextEntry(new ZipEntry(pathName));
|
||||
while ((len = fin.read(buf)) > 0) {
|
||||
zo.write(buf, 0, len);
|
||||
}
|
||||
fin.close();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
33
comm/Kernel/src/util/GoogleAuthTest.java
Executable file
33
comm/Kernel/src/util/GoogleAuthTest.java
Executable file
@@ -0,0 +1,33 @@
|
||||
package util;
|
||||
|
||||
/*
|
||||
* Not really a unit test- but it shows usage
|
||||
*/
|
||||
public class GoogleAuthTest {
|
||||
|
||||
public static void genSecretTest() {
|
||||
String secret = GoogleAuthenticator.generateSecretKey();
|
||||
String url = GoogleAuthenticator.getQRBarcodeURL("testuser", "testhost", secret);
|
||||
System.out.println("Please register " + url);
|
||||
System.out.println("Secret key is " + secret);
|
||||
}
|
||||
|
||||
// Change this to the saved secret from the running the above test.
|
||||
static String savedSecret = "4EWEHLG7CYXLSKTN";
|
||||
|
||||
public static void authTest() {
|
||||
// enter the code shown on device. Edit this and run it fast before the code
|
||||
// expires!
|
||||
long code = 350326;
|
||||
long t = System.currentTimeMillis();
|
||||
GoogleAuthenticator ga = new GoogleAuthenticator();
|
||||
ga.setWindowSize(5); // should give 5 * 30 seconds of grace...
|
||||
boolean r = ga.check_code(savedSecret, code, t);
|
||||
System.out.println("Check code = " + r);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
authTest();
|
||||
|
||||
}
|
||||
}
|
||||
140
comm/Kernel/src/util/GoogleAuthenticator.java
Executable file
140
comm/Kernel/src/util/GoogleAuthenticator.java
Executable file
@@ -0,0 +1,140 @@
|
||||
package util;
|
||||
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import org.apache.commons.codec.binary.Base32;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
|
||||
/**
|
||||
* Java Server side class for Google Authenticator's TOTP generator Thanks to
|
||||
* Enrico's blog for the sample code:
|
||||
*
|
||||
* @see http://thegreyblog.blogspot.com/2011/12/google-authenticator-using-it-in-your.html
|
||||
* @see http://code.google.com/p/google-authenticator
|
||||
* @see http://tools.ietf.org/id/draft-mraihi-totp-timebased-06.txt
|
||||
*/
|
||||
public class GoogleAuthenticator {
|
||||
|
||||
// taken from Google pam docs - we probably don't need to mess with these
|
||||
public static final int SECRET_SIZE = 10;
|
||||
|
||||
public static final String SEED = "H8GjEvTbW5oVSV7avFDdwIHqGlUYNzKFI7izOF8GwGEKIs2mEdN7vxRs2im5REaNCWGmcD2rvTex";
|
||||
|
||||
public static final String RANDOM_NUMBER_ALGORITHM = "SHA1PRNG";
|
||||
|
||||
int window_size = 3; // default 3 - max 17 (from google docs)最多可偏移的时间
|
||||
|
||||
/**
|
||||
* set the windows size. This is an integer value representing the number of 30
|
||||
* second windows we allow The bigger the window, the more tolerant of clock
|
||||
* skew we are.
|
||||
*
|
||||
* @param s window size - must be >=1 and <=17. Other values are ignored
|
||||
*/
|
||||
public void setWindowSize(int s) {
|
||||
if (s >= 1 && s <= 17)
|
||||
window_size = s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a random secret key. This must be saved by the server and associated
|
||||
* with the users account to verify the code displayed by Google Authenticator.
|
||||
* The user must register this secret on their device.
|
||||
*
|
||||
* @return secret key
|
||||
*/
|
||||
public static String generateSecretKey() {
|
||||
SecureRandom sr = null;
|
||||
try {
|
||||
sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);
|
||||
sr.setSeed(Base64.decodeBase64(SEED));
|
||||
byte[] buffer = sr.generateSeed(SECRET_SIZE);
|
||||
Base32 codec = new Base32();
|
||||
byte[] bEncodedKey = codec.encode(buffer);
|
||||
String encodedKey = new String(bEncodedKey);
|
||||
return encodedKey;
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
// should never occur... configuration error
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a URL that generates and displays a QR barcode. The user scans this
|
||||
* bar code with the Google Authenticator application on their smartphone to
|
||||
* register the auth code. They can also manually enter the secret if desired
|
||||
*
|
||||
* @param user user id (e.g. fflinstone)
|
||||
* @param host host or system that the code is for (e.g. myapp.com)
|
||||
* @param secret the secret that was previously generated for this user
|
||||
* @return the URL for the QR code to scan
|
||||
*/
|
||||
public static String getQRBarcodeURL(String user, String host, String secret) {
|
||||
String format = "https://www.google.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=otpauth://totp/%s@%s%%3Fsecret%%3D%s";
|
||||
return String.format(format, user, host, secret);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check the code entered by the user to see if it is valid
|
||||
*
|
||||
* @param secret The users secret.
|
||||
* @param code The code displayed on the users device
|
||||
* @param t The time in msec (System.currentTimeMillis() for example)
|
||||
* @return
|
||||
*/
|
||||
public boolean check_code(String secret, long code, long timeMsec) {
|
||||
Base32 codec = new Base32();
|
||||
byte[] decodedKey = codec.decode(secret);
|
||||
// convert unix msec time into a 30 second "window"
|
||||
// this is per the TOTP spec (see the RFC for details)
|
||||
long t = (timeMsec / 1000L) / 30L;
|
||||
// Window is used to check codes generated in the near past.
|
||||
// You can use this value to tune how far you're willing to go.
|
||||
for (int i = -window_size; i <= window_size; ++i) {
|
||||
long hash;
|
||||
try {
|
||||
hash = verify_code(decodedKey, t + i);
|
||||
} catch (Exception e) {
|
||||
// Yes, this is bad form - but
|
||||
// the exceptions thrown would be rare and a static configuration problem
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException(e.getMessage());
|
||||
// return false;
|
||||
}
|
||||
if (hash == code) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// The validation code is invalid.
|
||||
return false;
|
||||
}
|
||||
|
||||
private static int verify_code(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {
|
||||
byte[] data = new byte[8];
|
||||
long value = t;
|
||||
for (int i = 8; i-- > 0; value >>>= 8) {
|
||||
data[i] = (byte) value;
|
||||
}
|
||||
SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
|
||||
Mac mac = Mac.getInstance("HmacSHA1");
|
||||
mac.init(signKey);
|
||||
byte[] hash = mac.doFinal(data);
|
||||
int offset = hash[20 - 1] & 0xF;
|
||||
// We're using a long because Java hasn't got unsigned int.
|
||||
long truncatedHash = 0;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
truncatedHash <<= 8;
|
||||
// We are dealing with signed bytes:
|
||||
// we just keep the first byte.
|
||||
truncatedHash |= (hash[offset + i] & 0xFF);
|
||||
}
|
||||
truncatedHash &= 0x7FFFFFFF;
|
||||
truncatedHash %= 1000000;
|
||||
return (int) truncatedHash;
|
||||
}
|
||||
}
|
||||
55
comm/Kernel/src/util/HttpClient.java
Executable file
55
comm/Kernel/src/util/HttpClient.java
Executable file
@@ -0,0 +1,55 @@
|
||||
package util;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
public class HttpClient {
|
||||
public static String get(String url, int timeout) throws IOException {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
connection.setReadTimeout(timeout);
|
||||
connection.setConnectTimeout(timeout);
|
||||
connection.setRequestMethod("GET");
|
||||
|
||||
connection.connect();
|
||||
|
||||
InputStream is = connection.getInputStream();
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
|
||||
return readerToString(reader);
|
||||
}
|
||||
|
||||
public static String post(String url, int timeout, String in) throws IOException {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
connection.setReadTimeout(timeout);
|
||||
connection.setConnectTimeout(timeout);
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setRequestProperty("Content-Type", "application/json");
|
||||
|
||||
connection.setDoOutput(true);
|
||||
connection.getOutputStream().write(in.getBytes("UTF-8"));
|
||||
connection.connect();
|
||||
|
||||
InputStream is = connection.getInputStream();
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
|
||||
return readerToString(reader);
|
||||
}
|
||||
|
||||
private static String readerToString(BufferedReader reader) throws IOException {
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
String line;
|
||||
boolean isFirst = true;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
if (isFirst) {
|
||||
isFirst = false;
|
||||
} else {
|
||||
buffer.append("\r\n");
|
||||
}
|
||||
buffer.append(line);
|
||||
}
|
||||
reader.close();
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
133
comm/Kernel/src/util/IgnoreCaseString.java
Executable file
133
comm/Kernel/src/util/IgnoreCaseString.java
Executable file
@@ -0,0 +1,133 @@
|
||||
package util;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class IgnoreCaseString implements Comparable<IgnoreCaseString>, Serializable {
|
||||
/**
|
||||
* Member Description
|
||||
*/
|
||||
private static final long serialVersionUID = -247637491060007575L;
|
||||
|
||||
public static final IgnoreCaseString EMPTY = IgnoreCaseString.valueOf("");
|
||||
|
||||
/**
|
||||
* origStr string对象
|
||||
*/
|
||||
private final String origStr;
|
||||
|
||||
/**
|
||||
* lowerCaseStr string对象
|
||||
*/
|
||||
private final String lowerCaseStr;
|
||||
|
||||
// 需要抛出异常, Assert.assertEquals("d", IgnoreCaseString.valueOf(null).toString());
|
||||
public static IgnoreCaseString valueOf(String str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
return new IgnoreCaseString(str);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param value
|
||||
* String参数
|
||||
*/
|
||||
private IgnoreCaseString(String value) {
|
||||
if (value == null) {
|
||||
throw new NullPointerException("value不能为空");
|
||||
}
|
||||
|
||||
origStr = value;
|
||||
lowerCaseStr = value.toLowerCase();
|
||||
}
|
||||
|
||||
public char charAt(int i) {
|
||||
return origStr.charAt(i);
|
||||
}
|
||||
|
||||
public int compareTo(IgnoreCaseString o) {
|
||||
if (o == null) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (this == o) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return lowerCaseStr.compareTo(o.lowerCaseStr);
|
||||
}
|
||||
|
||||
public boolean contains(IgnoreCaseString other) {
|
||||
if (other == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return lowerCaseStr.contains(other.lowerCaseStr);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (obj instanceof IgnoreCaseString) {
|
||||
IgnoreCaseString other = (IgnoreCaseString) obj;
|
||||
return lowerCaseStr.equals(other.lowerCaseStr);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return byte数组 origStr转换成byte数组
|
||||
*/
|
||||
public byte[] getBytes() {
|
||||
return origStr.getBytes();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int PRIME = 31;
|
||||
int result = 1;
|
||||
result = PRIME * result + ((lowerCaseStr == null) ? 0 : lowerCaseStr.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
public int length() {
|
||||
return origStr.length();
|
||||
}
|
||||
|
||||
// TODO ztt
|
||||
// null的情况是否应该存在
|
||||
public String[] split(String regex) {
|
||||
if (origStr == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return origStr.split(regex);
|
||||
}
|
||||
|
||||
public char[] toCharArray() {
|
||||
return origStr.toCharArray();
|
||||
}
|
||||
|
||||
public String toLowerCase() {
|
||||
return origStr.toLowerCase();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return origStr;
|
||||
}
|
||||
|
||||
public String toUpperCase() {
|
||||
return origStr.toUpperCase();
|
||||
}
|
||||
|
||||
public String trim() {
|
||||
return origStr.trim();
|
||||
}
|
||||
|
||||
}
|
||||
259
comm/Kernel/src/util/ImageCut.java
Executable file
259
comm/Kernel/src/util/ImageCut.java
Executable file
@@ -0,0 +1,259 @@
|
||||
package util;
|
||||
|
||||
import java.awt.Graphics;
|
||||
import java.awt.Image;
|
||||
import java.awt.Toolkit;
|
||||
import java.awt.color.ColorSpace;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.awt.image.ColorConvertOp;
|
||||
import java.awt.image.CropImageFilter;
|
||||
import java.awt.image.FilteredImageSource;
|
||||
import java.awt.image.ImageFilter;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
public class ImageCut {
|
||||
|
||||
/**
|
||||
*
|
||||
* 缩放图像
|
||||
*
|
||||
* @param srcImageFile源图像文件地址
|
||||
*
|
||||
* @param result缩放后的图像地址
|
||||
*
|
||||
* @param scale缩放比例
|
||||
*
|
||||
* @param flag缩放选择
|
||||
* :true 放大; false 缩小;
|
||||
*/
|
||||
|
||||
public static void scale(String srcImageFile, String result, String type,double scale,
|
||||
|
||||
boolean flag) {
|
||||
|
||||
try {
|
||||
|
||||
BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
|
||||
|
||||
int width = src.getWidth(); // 得到源图宽
|
||||
|
||||
int height = src.getHeight(); // 得到源图长
|
||||
|
||||
if (flag) {// 放大
|
||||
|
||||
width = Double.valueOf((width * scale)).intValue();
|
||||
|
||||
height = Double.valueOf((height * scale)).intValue();
|
||||
|
||||
} else {// 缩小
|
||||
|
||||
width = Double.valueOf((width / scale)).intValue();
|
||||
|
||||
height = Double.valueOf((height / scale)).intValue();
|
||||
|
||||
}
|
||||
|
||||
Image image = src.getScaledInstance(width, height,
|
||||
|
||||
Image.SCALE_DEFAULT);
|
||||
|
||||
BufferedImage tag = new BufferedImage(width, height,
|
||||
|
||||
BufferedImage.TYPE_INT_RGB);
|
||||
|
||||
Graphics g = tag.getGraphics();
|
||||
|
||||
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
|
||||
|
||||
g.dispose();
|
||||
|
||||
ImageIO.write(tag, type, new File(result));// 输出到文件流
|
||||
|
||||
} catch (IOException e) {
|
||||
|
||||
e.printStackTrace();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 图像切割
|
||||
*
|
||||
* @param srcImageFile源图像地址
|
||||
*
|
||||
* @param descDir切片目标文件夹
|
||||
*
|
||||
* @param destWidth目标切片宽度
|
||||
*
|
||||
* @param destHeight目标切片高度
|
||||
*/
|
||||
|
||||
public static void cut(String srcImageFile, String descDir, int destWidth,
|
||||
|
||||
int destHeight) {
|
||||
|
||||
try {
|
||||
|
||||
Image img;
|
||||
|
||||
ImageFilter cropFilter; // 读取源图像
|
||||
|
||||
BufferedImage bi = ImageIO.read(new File(srcImageFile));
|
||||
|
||||
int srcWidth = bi.getHeight(); // 源图宽度
|
||||
|
||||
int srcHeight = bi.getWidth(); // 源图高度
|
||||
|
||||
if (srcWidth > destWidth && srcHeight > destHeight) {
|
||||
|
||||
Image image = bi.getScaledInstance(srcWidth, srcHeight,
|
||||
|
||||
Image.SCALE_DEFAULT);
|
||||
|
||||
destWidth = 200; // 切片宽度
|
||||
|
||||
destHeight = 150; // 切片高度
|
||||
|
||||
int cols = 0; // 切片横向数量
|
||||
|
||||
int rows = 0; // 切片纵向数量
|
||||
|
||||
// 计算切片的横向和纵向数量
|
||||
|
||||
if (srcWidth % destWidth == 0) {
|
||||
|
||||
cols = srcWidth / destWidth;
|
||||
|
||||
} else {
|
||||
|
||||
cols = (int) Math.floor(srcWidth / destWidth) + 1;
|
||||
|
||||
}
|
||||
|
||||
if (srcHeight % destHeight == 0) {
|
||||
|
||||
rows = srcHeight / destHeight;
|
||||
|
||||
} else {
|
||||
|
||||
rows = (int) Math.floor(srcHeight / destHeight) + 1;
|
||||
|
||||
}
|
||||
|
||||
// 循环建立切片
|
||||
|
||||
// 改进的想法:是否可用多线程加快切割速度
|
||||
|
||||
for (int i = 0; i < rows; i++) {
|
||||
|
||||
for (int j = 0; j < cols; j++) {
|
||||
|
||||
// 四个参数分别为图像起点坐标和宽高
|
||||
|
||||
// 即: CropImageFilter(int x,int y,int width,int height)
|
||||
|
||||
cropFilter = new CropImageFilter(j * 200, i * 150,
|
||||
|
||||
destWidth, destHeight);
|
||||
|
||||
img = Toolkit.getDefaultToolkit().createImage(
|
||||
|
||||
new FilteredImageSource(image.getSource(),
|
||||
|
||||
cropFilter));
|
||||
|
||||
BufferedImage tag = new BufferedImage(destWidth,
|
||||
|
||||
destHeight, BufferedImage.TYPE_INT_RGB);
|
||||
|
||||
Graphics g = tag.getGraphics();
|
||||
|
||||
g.drawImage(img, 0, 0, null); // 绘制缩小后的图
|
||||
|
||||
g.dispose();
|
||||
|
||||
// 输出为文件
|
||||
|
||||
ImageIO.write(tag, "JPEG", new File(descDir
|
||||
|
||||
+ "pre_map_" + i + "_" + j + ".jpg"));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
e.printStackTrace();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 图像类型转换GIF->JPG GIF->PNG PNG->JPG PNG->GIF(X)
|
||||
|
||||
public static void convert(String source, String result) {
|
||||
|
||||
try {
|
||||
|
||||
File f = new File(source);
|
||||
|
||||
f.canRead();
|
||||
|
||||
f.canWrite();
|
||||
|
||||
BufferedImage src = ImageIO.read(f);
|
||||
|
||||
ImageIO.write(src, "JPG", new File(result));
|
||||
|
||||
} catch (Exception e) {
|
||||
|
||||
// TODO Auto-generated catch block
|
||||
|
||||
e.printStackTrace();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 彩色转为黑白
|
||||
|
||||
public static void gray(String source, String result) {
|
||||
|
||||
try {
|
||||
|
||||
BufferedImage src = ImageIO.read(new File(source));
|
||||
|
||||
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
|
||||
|
||||
ColorConvertOp op = new ColorConvertOp(cs, null);
|
||||
|
||||
src = op.filter(src, null);
|
||||
|
||||
ImageIO.write(src, "JPEG", new File(result));
|
||||
|
||||
} catch (IOException e) {
|
||||
|
||||
e.printStackTrace();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
double s = 1024;
|
||||
int e = 500;
|
||||
double scale = s/e;
|
||||
String src = "E:\\apache-tomcat-6.0.37\\wtpwebapps\\mcp0917\\upload\\images\\2c9287a341ca74320141ca76181e0001\\5453797376338493.jpg";
|
||||
scale(src,"E:\\apache-tomcat-6.0.37\\wtpwebapps\\mcp0917\\upload\\images\\2c9287a341ca74320141ca76181e0001\\5453797376338493.jpg","jpg",scale,false);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user