initial commit: lottery 项目集(三工程统一管理)
- apps/lotteryServer, lotteryCapture, lotteryOpen 三个业务工程 - 忽略 archive/, tools/, infra/data/ 大目录与敏感配置文件 - 移除 lotteryServer 原嵌套 git,并入顶层统一管理
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
.idea/
|
||||
.settings
|
||||
target/
|
||||
.classpath
|
||||
.project
|
||||
*.iml
|
||||
*.class
|
||||
@@ -0,0 +1,39 @@
|
||||
# 玖盈
|
||||
|
||||
#### 项目介绍
|
||||
{**以下是码云平台说明,您可以替换为您的项目简介**
|
||||
码云是开源中国推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台
|
||||
无论是个人、团队、或是企业,都能够用码云实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)}
|
||||
|
||||
#### 软件架构
|
||||
软件架构说明
|
||||
|
||||
|
||||
#### 安装教程
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### 使用说明
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### 参与贡献
|
||||
|
||||
1. Fork 本项目
|
||||
2. 新建 Feat_xxx 分支
|
||||
3. 提交代码
|
||||
4. 新建 Pull Request
|
||||
|
||||
|
||||
#### 码云特技
|
||||
|
||||
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
|
||||
2. 码云官方博客 [blog.gitee.com](https://blog.gitee.com)
|
||||
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解码云上的优秀开源项目
|
||||
4. [GVP](https://gitee.com/gvp) 全称是码云最有价值开源项目,是码云综合评定出的优秀开源项目
|
||||
5. 码云官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
|
||||
6. 码云封面人物是一档用来展示码云会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
|
||||
@@ -0,0 +1,381 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>lotteryServer</groupId>
|
||||
<artifactId>lotteryServer</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<version>1.0.0</version>
|
||||
|
||||
<name>lotteryServer</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<spring.version>4.1.0.RELEASE</spring.version>
|
||||
<hibernate.version>4.2.13.Final</hibernate.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.10</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>2.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.plexus</groupId>
|
||||
<artifactId>plexus-utils</artifactId>
|
||||
<version>1.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.10</version>
|
||||
<type>jar</type>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-aop</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context-support</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-orm</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-aspects</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-redis</artifactId>
|
||||
<version>1.5.2.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.session</groupId>
|
||||
<artifactId>spring-session-data-redis</artifactId>
|
||||
<version>1.0.2.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-websocket</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-messaging</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>2.5.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-webmvc</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-core</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hibernate</groupId>
|
||||
<artifactId>hibernate-entitymanager</artifactId>
|
||||
<version>${hibernate.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.sf.json-lib</groupId>
|
||||
<artifactId>json-lib</artifactId>
|
||||
<version>2.4</version>
|
||||
<classifier>jdk15</classifier>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>commons-lang</groupId>
|
||||
<artifactId>commons-lang</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.im4java</groupId>
|
||||
<artifactId>im4java</artifactId>
|
||||
<version>1.4.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.mail</groupId>
|
||||
<artifactId>mail</artifactId>
|
||||
<version>1.4</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.quartz-scheduler</groupId>
|
||||
<artifactId>quartz</artifactId>
|
||||
<version>2.2.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>redis.clients</groupId>
|
||||
<artifactId>jedis</artifactId>
|
||||
<version>2.7.3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>1.10</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>servlet-api</artifactId>
|
||||
<version>3.0-alpha-1</version>
|
||||
<scope>provided</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>servlet-api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cryptix.jce</groupId>
|
||||
<artifactId>cryptix-jce-provider</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${basedir}\src\main\webapp\WEB-INF\lib\cryptix-jce-provider.jar</systemPath>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>net.contrapunctus.lzma</groupId>
|
||||
<artifactId>lzma-4.63-jio-0.95.jar</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${basedir}\src\main\webapp\WEB-INF\lib\lzma-4.63-jio-0.95.jar</systemPath>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.itrus</groupId>
|
||||
<artifactId>dinpayRsaSignAPI-2.7.10.jar</artifactId>
|
||||
<version>2.7.10</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${basedir}\src\main\webapp\WEB-INF\lib\dinpayRsaSignAPI-2.7.10.jar</systemPath>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bcprov-jdk15</artifactId>
|
||||
<version>1.46</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>druid</artifactId>
|
||||
<version>1.0.31</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>cn.beecloud</groupId>
|
||||
<artifactId>beecloud-java-sdk</artifactId>
|
||||
<version>3.4.11</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${basedir}\src\main\webapp\WEB-INF\lib\beecloud-java-sdk-3.4.11.jar</systemPath>
|
||||
</dependency>
|
||||
|
||||
<!-- LOGGING begins -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-api</artifactId>
|
||||
<version>1.7.7</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>1.1.2</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 代码直接调用log4j会被桥接到slf4j -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>log4j-over-slf4j</artifactId>
|
||||
<version>1.7.7</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- 代码直接调用common-logging会被桥接到slf4j -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jcl-over-slf4j</artifactId>
|
||||
<version>1.7.7</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- 代码直接调用java.util.logging会被桥接到slf4j -->
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>jul-to-slf4j</artifactId>
|
||||
<version>1.7.7</version>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<!-- LOGGING ends -->
|
||||
|
||||
<dependency>
|
||||
<groupId>com.warrenstrange</groupId>
|
||||
<artifactId>googleauth</artifactId>
|
||||
<version>0.5.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.google.zxing</groupId>
|
||||
<artifactId>core</artifactId>
|
||||
<version>3.2.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.zxing</groupId>
|
||||
<artifactId>javase</artifactId>
|
||||
<version>3.2.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>1.2.28</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mongodb</groupId>
|
||||
<artifactId>mongodb-driver-core</artifactId>
|
||||
<version>3.3.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>cn.yst</groupId>
|
||||
<artifactId>yst-java-sdk</artifactId>
|
||||
<version>1.0</version>
|
||||
<scope>system</scope>
|
||||
<systemPath>${basedir}\src\main\webapp\WEB-INF\lib\yst_api.jar</systemPath>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>lotteryServer</finalName>
|
||||
<plugins>
|
||||
<!-- 设置源文件编码方式 -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.3</version>
|
||||
<configuration>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
<encoding>UTF-8</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<!-- 解决资源文件的编码问题 -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>2.7</version>
|
||||
<configuration>
|
||||
<encoding>UTF-8</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<!-- 设置wabapp文件夹名称 -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>2.6</version>
|
||||
<configuration>
|
||||
<warSourceDirectory>src\main\webapp</warSourceDirectory>
|
||||
<!--<warSourceExcludes>**/*.js,**/*.css</warSourceExcludes>-->
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<!-- Tomcat 插件 -->
|
||||
<plugin>
|
||||
<groupId>org.apache.tomcat.maven</groupId>
|
||||
<artifactId>tomcat7-maven-plugin</artifactId>
|
||||
<version>2.1</version>
|
||||
<configuration>
|
||||
<port>8088</port>
|
||||
<path>/</path>
|
||||
<uriEncoding>UTF-8</uriEncoding>
|
||||
<finalName>/</finalName>
|
||||
<server>tomcat7</server>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<!--<!– YUI Compressor Maven压缩插件 –>-->
|
||||
<!--<plugin>-->
|
||||
<!--<groupId>net.alchim31.maven</groupId>-->
|
||||
<!--<artifactId>yuicompressor-maven-plugin</artifactId>-->
|
||||
<!--<version>1.3.0</version>-->
|
||||
<!--<executions>-->
|
||||
<!--<execution>-->
|
||||
<!--<phase>prepare-package</phase>-->
|
||||
<!--<goals>-->
|
||||
<!--<goal>compress</goal>-->
|
||||
<!--</goals>-->
|
||||
<!--</execution>-->
|
||||
<!--</executions>-->
|
||||
<!--<configuration>-->
|
||||
<!--<skip>false</skip>-->
|
||||
<!--<encoding>UTF-8</encoding>-->
|
||||
<!--<jswarn>false</jswarn>-->
|
||||
<!--<force>false</force>-->
|
||||
<!--<linebreakpos>-1</linebreakpos>-->
|
||||
<!--<nosuffix>true</nosuffix>-->
|
||||
|
||||
<!--<includes>-->
|
||||
<!--<include>**/*.js</include>-->
|
||||
<!--<include>**/*.css</include>-->
|
||||
<!--</includes>-->
|
||||
|
||||
<!--<excludes>-->
|
||||
<!--<exclude>**/*.min.js</exclude>-->
|
||||
<!--<exclude>**/*.min.css</exclude>-->
|
||||
<!--<exclude>**/*-min.css</exclude>-->
|
||||
<!--<exclude>**/*.min.css</exclude>-->
|
||||
<!--</excludes>-->
|
||||
<!--</configuration>-->
|
||||
<!--</plugin>-->
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,8 @@
|
||||
package activity.domains.content.biz;
|
||||
|
||||
|
||||
public interface ActivityBindService {
|
||||
|
||||
//boolean add(User uBean, String ip, String bindName, int bindBank, String bindCard);
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package activity.domains.content.biz;
|
||||
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import activity.domains.content.entity.ActivityCostBill;
|
||||
import activity.domains.content.vo.activity.ActivityCostDrawInfoVo;
|
||||
import activity.domains.content.vo.activity.ActivityRebateVo;
|
||||
|
||||
public interface ActivityCostService {
|
||||
//活动信息
|
||||
ActivityRebateVo getCostInfo(int type);
|
||||
|
||||
//领取信息
|
||||
ActivityCostDrawInfoVo getCostDarwInfo(int userId,String startTime ,String endTime);
|
||||
|
||||
//查询用户最近一条领取记录
|
||||
ActivityCostBill getLastCostBillInfo(int userId);
|
||||
|
||||
//查询当前IP最近一条领取记录
|
||||
ActivityCostBill getLastCostBillInfoByIp(String ip);
|
||||
|
||||
//得到今天的领取信息
|
||||
ActivityCostBill getToDayDrawInfo(int userId,String startTime ,String endTime);
|
||||
|
||||
//领取奖励
|
||||
boolean darwCostAward(int userId,Double costMoney,Double prizeMoney,Date now,String ip) ;
|
||||
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
// package activity.domains.content.biz;
|
||||
//
|
||||
// import java.util.List;
|
||||
//
|
||||
// import activity.domains.content.entity.ActivityPacketBill;
|
||||
// import activity.domains.content.entity.ActivityPacketInfo;
|
||||
//
|
||||
// public interface ActivityPacketService {
|
||||
//
|
||||
// /**
|
||||
// * 1,查询当前可以抢的红包
|
||||
// * 2,一个红包下面有N份
|
||||
// * 3,一个用户IP一个红包一天只能抢一次
|
||||
// * @return
|
||||
// */
|
||||
// public List<ActivityPacketInfo> getAvaliablePackets(int userId, String ip);
|
||||
//
|
||||
// /**
|
||||
// * 抢到一个红包
|
||||
// * @param packet
|
||||
// * @return
|
||||
// */
|
||||
// public ActivityPacketBill doGrabPacket(ActivityPacketInfo packetInfo, int userId, String ip);
|
||||
//
|
||||
// /**
|
||||
// * 发送红包
|
||||
// * @param count
|
||||
// * @param amount
|
||||
// * @param userId
|
||||
// * @return
|
||||
// */
|
||||
// public boolean doSendPacket(int count, double amount, int userId);
|
||||
//
|
||||
// /**
|
||||
// * 获取红包信息
|
||||
// * @param id
|
||||
// * @return
|
||||
// */
|
||||
// public ActivityPacketInfo get(int id);
|
||||
//
|
||||
// /**
|
||||
// * 一个红包每个ip一天只能抢一次
|
||||
// * @param ip
|
||||
// * @return
|
||||
// */
|
||||
// public ActivityPacketInfo validateIp(int packetId, String ip, List<ActivityPacketInfo> list);
|
||||
//
|
||||
// /**
|
||||
// * 领取红包需要检查流水是否满足
|
||||
// * 成功返回 -1 失败返回 最小金额
|
||||
// * @return
|
||||
// */
|
||||
// public double validateCost(int userId);
|
||||
//
|
||||
// }
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package activity.domains.content.biz;
|
||||
|
||||
import activity.domains.content.vo.activity.ActivityRechargeLoopVO;
|
||||
import lottery.web.WebJSON;
|
||||
|
||||
public interface ActivityRechargeLoopService {
|
||||
|
||||
ActivityRechargeLoopVO get(int userId);
|
||||
|
||||
boolean receive(WebJSON json, int userId, String ip, int step);
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
// package activity.domains.content.biz;
|
||||
//
|
||||
// import activity.domains.content.vo.activity.ActivitySalaryVO;
|
||||
// import lottery.web.WebJSON;
|
||||
//
|
||||
// public interface ActivitySalaryService {
|
||||
//
|
||||
// ActivitySalaryVO get(int userId, int type);
|
||||
//
|
||||
// boolean receive(WebJSON json, int userId, int type);
|
||||
//
|
||||
// }
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package activity.domains.content.biz;
|
||||
|
||||
import activity.domains.content.vo.activity.ActivitySignVO;
|
||||
import lottery.web.WebJSON;
|
||||
|
||||
public interface ActivitySignService {
|
||||
|
||||
/**
|
||||
* 获取当前连续签到情况
|
||||
*/
|
||||
ActivitySignVO getSignData(int userId);
|
||||
|
||||
/**
|
||||
* 签到,等于0:签到成功; 小于0:签到失败; 大于0:签到成功并返回成功领取的金额
|
||||
*/
|
||||
double sign(WebJSON json, int userId);
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package activity.domains.content.biz.impl;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import activity.domains.content.biz.ActivityBindService;
|
||||
|
||||
@Service
|
||||
public class ActivityBindServiceImpl implements ActivityBindService {
|
||||
|
||||
// @Autowired
|
||||
// private ActivityRebateWriteDao aRebateDao;
|
||||
//
|
||||
// @Autowired
|
||||
// private ActivityBindBillWriteDao aBindBillDao;
|
||||
|
||||
// @Override
|
||||
// public boolean add(User uBean, String ip, String bindName, int bindBank, String bindCard) {
|
||||
// ActivityRebate activity = aRebateDao.getByType(Global.ACTIVITY_REBATE_BIND);
|
||||
// if(activity != null) {
|
||||
// int userId = uBean.getId();
|
||||
// String registTime = uBean.getRegistTime();
|
||||
// double money = Double.parseDouble(activity.getRules());
|
||||
// String time = new Moment().toSimpleTime();
|
||||
// int status = 0;
|
||||
// ActivityBindBill entity = new ActivityBindBill(userId, registTime, ip, bindName, bindBank, bindCard, money, time, status);
|
||||
// return aBindBillDao.add(entity);
|
||||
// }
|
||||
// return false;
|
||||
// }
|
||||
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
package activity.domains.content.biz.impl;
|
||||
|
||||
|
||||
import activity.domains.content.biz.ActivityCostService;
|
||||
import activity.domains.content.dao.ActivityCostBillDao;
|
||||
import activity.domains.content.dao.ActivityRebateDao;
|
||||
import activity.domains.content.entity.ActivityCostBill;
|
||||
import activity.domains.content.entity.ActivityRebate;
|
||||
import activity.domains.content.vo.activity.ActivityCostDrawInfoVo;
|
||||
import activity.domains.content.vo.activity.ActivityRebateVo;
|
||||
import javautils.activity.PrizeUtils;
|
||||
import javautils.jdbc.PageList;
|
||||
import lottery.domains.content.biz.UserBillService;
|
||||
import lottery.domains.content.dao.UserDao;
|
||||
import lottery.domains.content.dao.read.UserBetsReadDao;
|
||||
import lottery.domains.content.entity.User;
|
||||
import lottery.domains.content.global.Global;
|
||||
import org.hibernate.criterion.Criterion;
|
||||
import org.hibernate.criterion.Order;
|
||||
import org.hibernate.criterion.Restrictions;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 消费佣金活动
|
||||
* <p>Title: ActivityCostServiceImpl</p>
|
||||
* <p>Description: </p>
|
||||
* @author James
|
||||
* @date 2018年2月4日
|
||||
*/
|
||||
@Service
|
||||
public class ActivityCostServiceImpl implements ActivityCostService{
|
||||
|
||||
@Autowired
|
||||
private ActivityRebateDao activityRebateDao;
|
||||
|
||||
@Autowired
|
||||
private ActivityCostBillDao activityCostBillDao;
|
||||
|
||||
@Autowired
|
||||
private UserBetsReadDao userBetsReadDao;
|
||||
|
||||
@Autowired
|
||||
private UserDao uDao;
|
||||
|
||||
@Autowired
|
||||
private UserBillService uBillService;
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public ActivityRebateVo getCostInfo(int type) {
|
||||
ActivityRebate bean = activityRebateDao.getByStatusAndType(type,Global.ACTIVITY_STATUS_OPEN);
|
||||
if(bean != null){
|
||||
ActivityRebateVo vo = new ActivityRebateVo();
|
||||
String res = bean.getRules();
|
||||
vo.setCostInfo(PrizeUtils.costConfigInfo(res));
|
||||
vo.setStatus(bean.getStatus());
|
||||
return vo;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public ActivityCostDrawInfoVo getCostDarwInfo(int userId, String startTime, String endTime) {
|
||||
ActivityCostDrawInfoVo vo = new ActivityCostDrawInfoVo();
|
||||
ActivityCostBill bill = activityCostBillDao.getDrawInfo(userId, startTime, endTime);
|
||||
if(bill != null){
|
||||
vo.setIsReceived(Global.ACTIVITY_COST_STATUS_Y);//已领取
|
||||
vo.setMayDraw(bill.getMoney());//已领金额
|
||||
vo.setTodayCost(bill.getTotalCost());//领取时消费的金额
|
||||
return vo;
|
||||
}else{
|
||||
double darwMoney = 0;
|
||||
ActivityRebate bean = activityRebateDao.getByStatusAndType(Global.ACTIVITY_REBATE_COST,
|
||||
Global.ACTIVITY_STATUS_OPEN);
|
||||
if(bean != null){
|
||||
double costMoney = userBetsReadDao.getBillingOrder(userId, startTime, endTime);
|
||||
vo.setTodayCost(costMoney);//当前消费金额
|
||||
String res = bean.getRules();
|
||||
darwMoney = PrizeUtils.costConfigPrize(res,costMoney);
|
||||
vo.setMayDraw(darwMoney);//可领金额
|
||||
if(darwMoney > 0){
|
||||
vo.setIsReceived(Global.ACTIVITY_COST_STATUS_K);//可领取
|
||||
}else{
|
||||
vo.setIsReceived(Global.ACTIVITY_COST_STATUS_B);//未达标
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public ActivityCostBill getLastCostBillInfo(int userId) {
|
||||
List<Criterion> criterions = new ArrayList<>();
|
||||
criterions.add(Restrictions.eq("userId", userId));
|
||||
List<Order> orders = new ArrayList<>();
|
||||
orders.add(Order.desc("id"));
|
||||
PageList pList = activityCostBillDao.search(criterions, orders, 0, 1);
|
||||
if(null != pList && pList.getList() != null && pList.getList().size() >0){
|
||||
ActivityCostBill costbill = (ActivityCostBill) pList.getList().get(0);
|
||||
return costbill;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public ActivityCostBill getToDayDrawInfo(int userId, String startTime, String endTime) {
|
||||
return activityCostBillDao.getDrawInfo(userId, startTime, endTime);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean darwCostAward(int userId,Double costMoney,Double prizeMoney,Date now,String ip) {
|
||||
User uBean = uDao.getById(userId);
|
||||
if(uBean != null) {
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
ActivityCostBill bill = new ActivityCostBill(userId,costMoney,prizeMoney,df.format(now),ip);
|
||||
boolean bFlag = activityCostBillDao.add(bill);
|
||||
if(bFlag) {
|
||||
boolean uFlag = uDao.updateLotteryMoney(userId, prizeMoney);
|
||||
if(uFlag) {
|
||||
String remarks = "消费奖励礼金";
|
||||
Integer refType = 1; // 其他活动类型
|
||||
return uBillService.addActivityBill(uBean, Global.BILL_ACCOUNT_LOTTERY, prizeMoney,
|
||||
refType, remarks);
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public ActivityCostBill getLastCostBillInfoByIp(String ip) {
|
||||
List<Criterion> criterions = new ArrayList<>();
|
||||
criterions.add(Restrictions.eq("drawIp", ip));
|
||||
List<Order> orders = new ArrayList<>();
|
||||
orders.add(Order.desc("id"));
|
||||
PageList pList = activityCostBillDao.search(criterions, orders, 0, 1);
|
||||
if(null != pList && pList.getList() != null && pList.getList().size() >0){
|
||||
ActivityCostBill costbill = (ActivityCostBill) pList.getList().get(0);
|
||||
return costbill;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
// package activity.domains.content.biz.impl;
|
||||
//
|
||||
// import java.text.DecimalFormat;
|
||||
// import java.util.ArrayList;
|
||||
// import java.util.List;
|
||||
// import java.util.Random;
|
||||
//
|
||||
// import javautils.StringUtil;
|
||||
// import javautils.date.DateUtil;
|
||||
// import javautils.date.Moment;
|
||||
// import lottery.domains.content.biz.UserBillService;
|
||||
// import lottery.domains.content.dao.ActivityPacketBillWriteDao;
|
||||
// import lottery.domains.content.dao.ActivityPacketInfoDao;
|
||||
// import lottery.domains.content.dao.UserDao;
|
||||
// import lottery.domains.content.dao.UserLotteryReportDao;
|
||||
// import lottery.domains.content.entity.User;
|
||||
// import lottery.domains.content.entity.UserLotteryReport;
|
||||
// import lottery.domains.content.global.Global;
|
||||
// import net.sf.json.JSONArray;
|
||||
//
|
||||
// import org.slf4j.Logger;
|
||||
// import org.slf4j.LoggerFactory;
|
||||
// import org.springframework.beans.factory.annotation.Autowired;
|
||||
// import org.springframework.data.redis.core.RedisTemplate;
|
||||
// import org.springframework.stereotype.Service;
|
||||
//
|
||||
// import activity.domains.content.biz.ActivityPacketService;
|
||||
// import activity.domains.content.dao.write.ActivityRebateWriteDao;
|
||||
// import activity.domains.content.entity.ActivityPacketBill;
|
||||
// import activity.domains.content.entity.ActivityPacketInfo;
|
||||
// import activity.domains.content.entity.ActivityRebate;
|
||||
// import activity.domains.content.entity.activity.RebateRulesPacket;
|
||||
//
|
||||
// @Service
|
||||
// public class ActivityPacketServiceImpl implements ActivityPacketService {
|
||||
//
|
||||
// @Autowired
|
||||
// private UserDao userDao;
|
||||
//
|
||||
// @Autowired
|
||||
// private ActivityPacketBillWriteDao activityPacketBillDao;
|
||||
//
|
||||
// @Autowired
|
||||
// private ActivityPacketInfoDao activityPacketInfoDao;
|
||||
//
|
||||
// @Autowired
|
||||
// private UserLotteryReportDao uLotteryReportDao;
|
||||
//
|
||||
// @Autowired
|
||||
// private ActivityRebateWriteDao aRebateDao;
|
||||
//
|
||||
// @Autowired
|
||||
// private UserBillService uBillService;
|
||||
//
|
||||
// @Autowired
|
||||
// private RedisTemplate<String, Object> redisTemplate;
|
||||
//
|
||||
// private static Logger logger = LoggerFactory.getLogger(ActivityPacketServiceImpl.class);
|
||||
//
|
||||
// @SuppressWarnings("unchecked")
|
||||
// List<RebateRulesPacket> listRules(String rules) {
|
||||
// return (List<RebateRulesPacket>) JSONArray.toCollection(
|
||||
// JSONArray.fromObject(rules), RebateRulesPacket.class);
|
||||
// }
|
||||
//
|
||||
// double getTotalCost(String startTime, String endTime, int userId) {
|
||||
// String sDate = new Moment().fromTime(startTime).toSimpleDate();
|
||||
// String eDate = new Moment().fromTime(endTime).add(1, "days").toSimpleDate();
|
||||
// int[] ids = { userId };
|
||||
// List<UserLotteryReport> lotteryDayList = uLotteryReportDao.getDayList(ids, sDate, eDate);
|
||||
// double totalCost = 0;
|
||||
// for (UserLotteryReport tmpBean : lotteryDayList) {
|
||||
// totalCost += tmpBean.getBillingOrder();
|
||||
// }
|
||||
// return totalCost;
|
||||
// }
|
||||
//
|
||||
// private ActivityPacketInfo generatePacketInfo(int count, double amount, int userId) {
|
||||
// ActivityPacketInfo packetInfo = new ActivityPacketInfo();
|
||||
// packetInfo.setAmount(amount);
|
||||
// packetInfo.setCount(count);
|
||||
// packetInfo.setStatus(ActivityPacketInfo.PacketStatus.AVALIABLE.get());
|
||||
// packetInfo.setTime(DateUtil.getCurrentTime());
|
||||
// packetInfo.setUserId(userId);
|
||||
// packetInfo.setType(ActivityPacketInfo.PacketType.USER_PACKET.get());
|
||||
// activityPacketInfoDao.save(packetInfo);
|
||||
// return packetInfo;
|
||||
// }
|
||||
//
|
||||
// private void splitPacket(int count, double amount, int packetInfoId, List<ActivityPacketBill> packets) {
|
||||
// double seed = amount/count;
|
||||
// double start = 0;
|
||||
// DecimalFormat df = new DecimalFormat("0.00");
|
||||
// Random random = new Random();
|
||||
// for (int i = 0; i < count; i++) {
|
||||
// double d = random.nextDouble();
|
||||
// if(d == 0.0){
|
||||
// d = 0.1;
|
||||
// }
|
||||
// d = d * seed;
|
||||
// double money = Double.parseDouble(df.format(d));
|
||||
// start += money;
|
||||
//
|
||||
// ActivityPacketBill packet = new ActivityPacketBill();
|
||||
// packet.setAmount(money);
|
||||
// packet.setPacketId(packetInfoId);
|
||||
// packet.setStatus(ActivityPacketInfo.PacketStatus.AVALIABLE.get());
|
||||
// packets.add(packet);
|
||||
// }
|
||||
// double surplus = Double.parseDouble(df.format((amount - start)/count));//还剩余多少钱
|
||||
//
|
||||
// start = 0;
|
||||
// for (ActivityPacketBill activityPacketBill : packets) {
|
||||
// double newAmount = activityPacketBill.getAmount() + surplus;
|
||||
// activityPacketBill.setAmount(newAmount);
|
||||
// start += newAmount;
|
||||
// }
|
||||
//
|
||||
// ActivityPacketBill firstBill = packets.get(0);
|
||||
// if(amount - start != 0){
|
||||
// firstBill.setAmount(firstBill.getAmount() + (amount - start));
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public List<ActivityPacketInfo> getAvaliablePackets(int userId, String ip) {
|
||||
// List<ActivityPacketInfo> list = activityPacketInfoDao.find(ActivityPacketInfo.PacketStatus.AVALIABLE.get(), userId, ip);
|
||||
// return list;
|
||||
// }
|
||||
//
|
||||
//
|
||||
// /**
|
||||
// * <p>1.为解决并发问题 每次获取红包前先判断状态是否可用</p>
|
||||
// * <p>2.获取红包后更新PacketInfo状态</p>
|
||||
// * <p>3.返回null提示用户已经抢光并且更新数据 否则返回正常红包</p>
|
||||
// * <p>4.更新用户余额,添加用户账单</p>
|
||||
//
|
||||
// @Override
|
||||
// public ActivityPacketBill doGrabPacket(ActivityPacketInfo packetInfo, int userId, String ip) {
|
||||
// if(packetInfo.getStatus() == ActivityPacketInfo.PacketStatus.FINISH.get()){
|
||||
// return null;
|
||||
// }
|
||||
// logger.info("获得红包:{}", packetInfo.getId());
|
||||
//
|
||||
// List<ActivityPacketBill> packets = packetInfo.getPackets(activityPacketBillDao, redisTemplate, true);
|
||||
// ActivityPacketBill getPacket = null;
|
||||
//
|
||||
// for (ActivityPacketBill activityPacketBill : packets) {
|
||||
// if(activityPacketBill.getStatus() == ActivityPacketInfo.PacketStatus.AVALIABLE.get()){
|
||||
// getPacket = activityPacketBill;
|
||||
// activityPacketBill.setStatus(ActivityPacketInfo.PacketStatus.FINISH.get());
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if(getPacket != null){
|
||||
// logger.info("抢红包成功,获得红包:{} 下一份:{} 金额:{}", packetInfo.getId(), getPacket.getId(), getPacket.getAmount());
|
||||
// //1. 更新被抢红包状态
|
||||
// updatePacketBill(userId, getTodayCost(userId), ip, getPacket);
|
||||
// //2. 更新用余额,新增用户账单
|
||||
// updateBalanceAndBill(userId, getPacket, packetInfo.getType());
|
||||
// //3. 更新红包缓存
|
||||
// packetInfo.refreshCache(redisTemplate, packets);
|
||||
// //4. 检查红包是否被抢光,如果被抢完则删除缓存 更新DB 状态
|
||||
// checkPacketInfoStatus(packetInfo, packets, userId);
|
||||
// }
|
||||
//
|
||||
// return getPacket;
|
||||
// }
|
||||
//
|
||||
// private void checkPacketInfoStatus(ActivityPacketInfo packetInfo, List<ActivityPacketBill> packets, int userId) {
|
||||
// boolean finish = true;
|
||||
// for (ActivityPacketBill activityPacketBill : packets) {
|
||||
// if(activityPacketBill.getStatus() == ActivityPacketInfo.PacketStatus.AVALIABLE.get()){
|
||||
// finish = false;
|
||||
// }
|
||||
// }
|
||||
// if(finish){
|
||||
// packetInfo.deleteCache(redisTemplate);
|
||||
// packetInfo.setStatus(ActivityPacketInfo.PacketStatus.FINISH.get());
|
||||
// activityPacketInfoDao.update(packetInfo);
|
||||
// logger.info("红包:{} 已经被抢完,删除缓存,更新DB...", packetInfo.getId());
|
||||
// }
|
||||
// }
|
||||
//
|
||||
//
|
||||
// //计入用户流水 更新用户金额
|
||||
// private void updateBalanceAndBill(int userId, ActivityPacketBill activityPacketBill, int packetType) {
|
||||
// User uBean = userDao.getById(userId);
|
||||
// boolean uFlag = userDao.updateLotteryMoney(userId, activityPacketBill.getAmount());
|
||||
// String remarks = "抢红包";
|
||||
// Integer refType = 1; // 其他活动类型
|
||||
// if(uFlag) {
|
||||
// uBillService.addPacketBill(uBean, Global.BILL_ACCOUNT_LOTTERY, activityPacketBill.getAmount(), refType, remarks);
|
||||
// }
|
||||
// if(packetType == ActivityPacketInfo.PacketType.SYSTEM_PACKET.get()){//如果是系统红包 则计入优惠活动
|
||||
// uBillService.addActivityBill(uBean, Global.BILL_ACCOUNT_LOTTERY, activityPacketBill.getAmount(), refType, remarks);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// private void updatePacketBill(int userId, double cost, String ip, ActivityPacketBill activityPacketBill) {
|
||||
// activityPacketBill.setStatus(ActivityPacketInfo.PacketStatus.FINISH.get());
|
||||
// activityPacketBill.setUserId(userId);
|
||||
// activityPacketBill.setTime(DateUtil.getCurrentTime());
|
||||
// activityPacketBill.setCost(cost);
|
||||
// activityPacketBill.setIp(ip);
|
||||
// activityPacketBillDao.update(activityPacketBill);
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public boolean doSendPacket(int count, double amount, int userId) {
|
||||
// ActivityPacketInfo packetInfo = generatePacketInfo(count, amount, userId);
|
||||
// int packetInfoId = packetInfo.getId();
|
||||
//
|
||||
// List<ActivityPacketBill> packets = new ArrayList<ActivityPacketBill>();
|
||||
// splitPacket(count, amount, packetInfoId, packets);
|
||||
// for (ActivityPacketBill activityPacketBill : packets) {
|
||||
// activityPacketBillDao.save(activityPacketBill);
|
||||
// }
|
||||
//
|
||||
// //计入用户流水 更新用户金额
|
||||
// User uBean = userDao.getById(userId);
|
||||
// boolean uFlag = userDao.updateLotteryMoney(userId, -amount);
|
||||
// if(uFlag) {
|
||||
// String remarks = "派发红包";
|
||||
// Integer refType = 1; // 其他活动类型
|
||||
// return uBillService.addPacketBill(uBean, Global.BILL_ACCOUNT_LOTTERY, -amount, refType, remarks);
|
||||
// }
|
||||
// return true;
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public ActivityPacketInfo get(int id) {
|
||||
// return activityPacketInfoDao.get(id);
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public ActivityPacketInfo validateIp(int packetId, String ip, List<ActivityPacketInfo> list) {
|
||||
// ActivityPacketInfo packetInfo = null;
|
||||
// for (ActivityPacketInfo activityPacketInfo : list) {
|
||||
// if(packetId == activityPacketInfo.getId()){
|
||||
// packetInfo = activityPacketInfo;
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// boolean exist = activityPacketBillDao.isExist(ip, packetId);
|
||||
// if(exist){
|
||||
// logger.info("Packetid:{} with ip :{} weather exist:{} !", packetId, ip , exist);
|
||||
// packetInfo = null;
|
||||
// }
|
||||
// return packetInfo;
|
||||
// }
|
||||
//
|
||||
// public double validateCost(int userId) {
|
||||
// ActivityRebate activity = aRebateDao.getByType(Global.ACTIVITY_REBATE_PACKET);
|
||||
// double minCost = 0;
|
||||
// if(StringUtil.isNotNull(activity.getRules())){
|
||||
// minCost = listRules(activity.getRules()).get(0).getCost();//最低消费额度
|
||||
// }
|
||||
// double todayCost = getTodayCost(userId);
|
||||
// return todayCost >= minCost ? -1 : minCost;
|
||||
// }
|
||||
//
|
||||
// private double getTodayCost(int userId) {
|
||||
// double todayCost = 0;
|
||||
// String today = new Moment().toSimpleDate();
|
||||
// UserLotteryReport todayReport = uLotteryReportDao.get(userId, today);
|
||||
// if(todayReport != null){
|
||||
// todayCost = todayReport.getBillingOrder();
|
||||
// }
|
||||
// return todayCost;
|
||||
// }
|
||||
//
|
||||
// }
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
package activity.domains.content.biz.impl;
|
||||
|
||||
import activity.domains.content.biz.ActivityRechargeLoopService;
|
||||
import activity.domains.content.dao.ActivityRebateDao;
|
||||
import activity.domains.content.dao.ActivityRechargeLoopBillDao;
|
||||
import activity.domains.content.entity.ActivityRebate;
|
||||
import activity.domains.content.entity.ActivityRechargeLoopBill;
|
||||
import activity.domains.content.entity.activity.RebateRulesRechargeLoop;
|
||||
import activity.domains.content.vo.activity.ActivityRechargeLoopVO;
|
||||
import javautils.date.Moment;
|
||||
import javautils.math.MathUtil;
|
||||
import lottery.domains.content.biz.UserBillService;
|
||||
import lottery.domains.content.dao.UserDao;
|
||||
import lottery.domains.content.dao.UserRechargeDao;
|
||||
import lottery.domains.content.dao.read.UserBetsReadDao;
|
||||
import lottery.domains.content.entity.User;
|
||||
import lottery.domains.content.entity.UserRecharge;
|
||||
import lottery.domains.content.global.Global;
|
||||
import lottery.web.WebJSON;
|
||||
import net.sf.json.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class ActivityRechargeLoopServiceImpl implements ActivityRechargeLoopService {
|
||||
|
||||
@Autowired
|
||||
private UserDao uDao;
|
||||
|
||||
@Autowired
|
||||
private ActivityRebateDao aRebateDao;
|
||||
|
||||
@Autowired
|
||||
private ActivityRechargeLoopBillDao aRechargeLoopBillDao;
|
||||
|
||||
@Autowired
|
||||
private UserBetsReadDao uBetsReadDao;
|
||||
|
||||
@Autowired
|
||||
private UserRechargeDao uRechargeDao;
|
||||
|
||||
@Autowired
|
||||
private UserBillService uBillService;
|
||||
|
||||
RebateRulesRechargeLoop listRules(String rules) {
|
||||
return (RebateRulesRechargeLoop) JSONObject.toBean(JSONObject.fromObject(rules), RebateRulesRechargeLoop.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(readOnly = true)
|
||||
public ActivityRechargeLoopVO get(int userId) {
|
||||
ActivityRebate activity = aRebateDao.getByType(Global.ACTIVITY_REBATE_RECHARGE_LOOP);
|
||||
if(activity != null) {
|
||||
Moment thisTime = new Moment();
|
||||
ActivityRechargeLoopVO bean = new ActivityRechargeLoopVO();
|
||||
RebateRulesRechargeLoop rules = listRules(activity.getRules());
|
||||
List<ActivityRechargeLoopBill> bList = aRechargeLoopBillDao.getByDate(userId, thisTime.toSimpleDate());
|
||||
int s2Times = 0;
|
||||
String s2StartTime = new Moment().toSimpleDate();
|
||||
for (ActivityRechargeLoopBill tmpBean : bList) {
|
||||
if(tmpBean.getStep() == 1) {
|
||||
bean.setS1Recharge(tmpBean.getTotalMoney());
|
||||
bean.setS1Cost(tmpBean.getTotalCost());
|
||||
bean.setS1Reward(tmpBean.getMoney());
|
||||
bean.setS1Available(false);
|
||||
bean.setS1Received(true);
|
||||
s2StartTime = tmpBean.getTime();
|
||||
}
|
||||
if(tmpBean.getStep() == 2) {
|
||||
s2Times++;
|
||||
s2StartTime = tmpBean.getTime();
|
||||
}
|
||||
if(tmpBean.getStep() == 3) {
|
||||
bean.setS3Available(false);
|
||||
bean.setS3Received(true);
|
||||
}
|
||||
}
|
||||
// 判断第一步,没有领取记录
|
||||
if(!bean.isS1Received()) {
|
||||
List<UserRecharge> rList = uRechargeDao.listByDate(userId, thisTime.toSimpleDate());
|
||||
for (UserRecharge tmpBean : rList) {
|
||||
if(tmpBean.getMoney() >= rules.getS1Recharge()) {
|
||||
bean.setS1Recharge(tmpBean.getMoney());
|
||||
String startTime = tmpBean.getPayTime();
|
||||
String endTime = new Moment().toSimpleTime();
|
||||
double s1Cost = uBetsReadDao.getBillingOrder(userId, startTime, endTime);
|
||||
double s1CostLimit = tmpBean.getMoney() * rules.getS1Cost() / 100;
|
||||
s1CostLimit = MathUtil.doubleFormat(s1CostLimit, 3);
|
||||
bean.setS1Cost(s1Cost);
|
||||
double s1Reward = tmpBean.getMoney() * rules.getS1Reward() / 100;
|
||||
s1Reward = MathUtil.doubleFormat(s1Reward, 3);
|
||||
bean.setS1Reward(s1Reward);
|
||||
if(s1Cost >= s1CostLimit) {
|
||||
bean.setS1Available(true);
|
||||
bean.setS1Received(false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 判断第二步
|
||||
if(bean.isS1Received()) {
|
||||
if(!bean.isS3Received()) {
|
||||
boolean hasNext = true;
|
||||
bean.setS2Times(s2Times);
|
||||
if(s2Times == rules.getS2Times()) {
|
||||
hasNext = false;
|
||||
bean.setS2Available(false);
|
||||
bean.setS2Received(true);
|
||||
}
|
||||
if(hasNext) {
|
||||
String s2EndTime = new Moment().toSimpleTime();
|
||||
// 消费量
|
||||
double s2Cost = uBetsReadDao.getBillingOrder(userId, s2StartTime, s2EndTime);
|
||||
bean.setS2Cost(s2Cost);
|
||||
if(s2Cost >= rules.getS2Cost()) {
|
||||
bean.setS2Available(true);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
bean.setS2Available(false);
|
||||
bean.setS2Received(true);
|
||||
}
|
||||
} else {
|
||||
bean.setS2Available(false);
|
||||
bean.setS2Received(false);
|
||||
}
|
||||
// 判断第三步
|
||||
if(!bean.isS3Received()) {
|
||||
if(bean.isS1Received() && s2Times >= rules.getS3Limit()) {
|
||||
bean.setS3Available(true);
|
||||
bean.setS3Received(false);
|
||||
}
|
||||
}
|
||||
// 活动规则
|
||||
bean.setRules(rules);
|
||||
return bean;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean receive(WebJSON json, int userId, String ip, int step) {
|
||||
ActivityRechargeLoopVO activity = get(userId);
|
||||
if(activity != null) {
|
||||
// 领取第一步
|
||||
if(step == 1) {
|
||||
if(activity.isS1Received()) {
|
||||
json.set(2, "2-4002");
|
||||
return false;
|
||||
}
|
||||
if(activity.isS1Available()) {
|
||||
// s1 bill
|
||||
User uBean = uDao.getById(userId);
|
||||
if(uBean != null) {
|
||||
double totalMoney = activity.getS1Recharge();
|
||||
double totalCost = activity.getS1Cost();
|
||||
double money = activity.getS1Reward();
|
||||
String time = new Moment().toSimpleTime();
|
||||
ActivityRechargeLoopBill entity = new ActivityRechargeLoopBill(userId, ip, step, totalMoney, totalCost, money, time);
|
||||
boolean bFlag = aRechargeLoopBillDao.add(entity);
|
||||
if(bFlag) {
|
||||
boolean uFlag = uDao.updateLotteryMoney(uBean.getId(), money);
|
||||
if(uFlag) {
|
||||
String remarks = "开业大酬宾,连环活动嗨不停。";
|
||||
Integer refType = 1; // 其他活动类型
|
||||
uBillService.addActivityBill(uBean, Global.BILL_ACCOUNT_LOTTERY, money, refType, remarks);
|
||||
}
|
||||
return uFlag;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
json.set(2, "2-4007");
|
||||
}
|
||||
}
|
||||
// 领取第二步
|
||||
if(step == 2) {
|
||||
if(activity.isS2Received()) {
|
||||
json.set(2, "2-4002");
|
||||
return false;
|
||||
}
|
||||
if(activity.isS2Available()) {
|
||||
// s2 bill
|
||||
User uBean = uDao.getById(userId);
|
||||
if(uBean != null) {
|
||||
double totalMoney = 0;
|
||||
double totalCost = activity.getS2Cost();
|
||||
double money = activity.getRules().getS2Reward();
|
||||
String time = new Moment().toSimpleTime();
|
||||
ActivityRechargeLoopBill entity = new ActivityRechargeLoopBill(userId, ip, step, totalMoney, totalCost, money, time);
|
||||
boolean bFlag = aRechargeLoopBillDao.add(entity);
|
||||
if(bFlag) {
|
||||
boolean uFlag = uDao.updateLotteryMoney(uBean.getId(), money);
|
||||
if(uFlag) {
|
||||
String remarks = "开业大酬宾,连环活动嗨不停。";
|
||||
Integer refType = 1; // 其他活动类型
|
||||
uBillService.addActivityBill(uBean, Global.BILL_ACCOUNT_LOTTERY, money, refType, remarks);
|
||||
}
|
||||
return uFlag;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
json.set(2, "2-4005");
|
||||
}
|
||||
}
|
||||
// 领取第三步
|
||||
if(step == 3) {
|
||||
if(activity.isS3Received()) {
|
||||
json.set(2, "2-4002");
|
||||
return false;
|
||||
}
|
||||
if(activity.isS3Available()) {
|
||||
// s3 bill
|
||||
User uBean = uDao.getById(userId);
|
||||
if(uBean != null) {
|
||||
double totalMoney = 0;
|
||||
double totalCost = 0;
|
||||
double money = activity.getRules().getS3Reward();
|
||||
String time = new Moment().toSimpleTime();
|
||||
ActivityRechargeLoopBill entity = new ActivityRechargeLoopBill(userId, ip, step, totalMoney, totalCost, money, time);
|
||||
boolean bFlag = aRechargeLoopBillDao.add(entity);
|
||||
if(bFlag) {
|
||||
boolean uFlag = uDao.updateLotteryMoney(uBean.getId(), money);
|
||||
if(uFlag) {
|
||||
String remarks = "开业大酬宾,连环活动嗨不停。";
|
||||
Integer refType = 1; // 其他活动类型
|
||||
uBillService.addActivityBill(uBean, Global.BILL_ACCOUNT_LOTTERY, money, refType, remarks);
|
||||
}
|
||||
return uFlag;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
json.set(2, "2-4007");
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
// package activity.domains.content.biz.impl;
|
||||
//
|
||||
// import java.util.List;
|
||||
//
|
||||
// import org.springframework.beans.factory.annotation.Autowired;
|
||||
// import org.springframework.stereotype.Service;
|
||||
//
|
||||
// import javautils.date.Moment;
|
||||
// import activity.domains.content.biz.ActivitySalaryService;
|
||||
// import activity.domains.content.dao.ActivityRebateDao;
|
||||
// import activity.domains.content.dao.ActivitySalaryBillDao;
|
||||
// import activity.domains.content.entity.ActivityRebate;
|
||||
// import activity.domains.content.entity.ActivitySalaryBill;
|
||||
// import activity.domains.content.entity.activity.RebateRulesSalary;
|
||||
// import activity.domains.content.vo.activity.ActivitySalaryVO;
|
||||
// import lottery.domains.content.biz.UserBillService;
|
||||
// import lottery.domains.content.biz.UserLotteryReportService;
|
||||
// import lottery.domains.content.dao.UserDao;
|
||||
// import lottery.domains.content.dao.UserLotteryReportDao;
|
||||
// import lottery.domains.content.entity.User;
|
||||
// import lottery.domains.content.global.Global;
|
||||
// import lottery.domains.content.vo.bill.UserLotteryReportVO;
|
||||
// import lottery.web.WebJSON;
|
||||
// import net.sf.json.JSONArray;
|
||||
//
|
||||
// @Service
|
||||
// public class ActivitySalaryServiceImpl implements ActivitySalaryService {
|
||||
//
|
||||
// @Autowired
|
||||
// private UserDao uDao;
|
||||
//
|
||||
// @Autowired
|
||||
// private ActivityRebateDao aRebateDao;
|
||||
//
|
||||
// @Autowired
|
||||
// private ActivitySalaryBillDao aSalaryBillDao;
|
||||
//
|
||||
// @Autowired
|
||||
// private UserLotteryReportDao mUserLotteryReportDao;
|
||||
//
|
||||
// @Autowired
|
||||
// private UserBillService uBillService;
|
||||
//
|
||||
// @Autowired
|
||||
// private UserLotteryReportService uLotteryReportService;
|
||||
//
|
||||
// @SuppressWarnings("unchecked")
|
||||
// List<RebateRulesSalary> listRules(String rules) {
|
||||
// return (List<RebateRulesSalary>) JSONArray.toCollection(JSONArray.fromObject(rules), RebateRulesSalary.class);
|
||||
// }
|
||||
//
|
||||
// UserLotteryReportVO report(int userId, String sTime, String eTime) {
|
||||
// List<UserLotteryReportVO> report = uLotteryReportService.report(userId, sTime, eTime);
|
||||
// return report.get(0);
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public ActivitySalaryVO get(int userId, int type) {
|
||||
// // 统计活跃会员人数
|
||||
// List<User> list = uDao.getUserLower(userId);
|
||||
// int[] targetUsers = new int[list.size()];
|
||||
// for (int i = 0, j = list.size(); i < j; i++) {
|
||||
// targetUsers[i] = list.get(i).getId();
|
||||
// }
|
||||
// String yesterday = new Moment().subtract(1,"d").toSimpleDate();
|
||||
// String today = new Moment().toSimpleDate();
|
||||
// int activityUser = mUserLotteryReportDao.getActivityUser(targetUsers, yesterday, today);
|
||||
//
|
||||
// ActivityRebate activity = null;
|
||||
// if(type == 1) {
|
||||
// activity = aRebateDao.getByType(Global.ACTIVITY_REBATE_SALARY_ZHISHU);
|
||||
// }
|
||||
// if(type == 2) {
|
||||
// activity = aRebateDao.getByType(Global.ACTIVITY_REBATE_SALARY_ZONGDAI);
|
||||
// }
|
||||
// if(activity != null) {
|
||||
// // 这个是计算昨天的消费量
|
||||
// Moment thisTime = new Moment();
|
||||
// Moment lastTime = new Moment().subtract(1, "days");
|
||||
// UserLotteryReportVO report = report(userId, lastTime.toSimpleDate(), thisTime.toSimpleDate());
|
||||
// double totalMoney = report.getBillingOrder();
|
||||
// //double totalProfit = report.getPrize() + report.getSpendReturn() + report.getProxyReturn() + report.getActivity() - report.getBillingOrder();
|
||||
// List<RebateRulesSalary> rlist = listRules(activity.getRules());
|
||||
// boolean isReceived = false;
|
||||
// boolean hasRecord = aSalaryBillDao.hasRecord(userId, type, lastTime.toSimpleDate());
|
||||
// if(hasRecord) {
|
||||
// isReceived = true;
|
||||
// }
|
||||
// ActivitySalaryVO bean = new ActivitySalaryVO();
|
||||
// bean.setTotalMoney(totalMoney);
|
||||
// bean.setRlist(rlist);
|
||||
// bean.setPeople(activityUser);
|
||||
// bean.setReceived(isReceived);
|
||||
// return bean;
|
||||
// }
|
||||
// return null;
|
||||
// }
|
||||
//
|
||||
// @Override
|
||||
// public synchronized boolean receive(WebJSON json, int userId, int type) {
|
||||
// ActivitySalaryVO activity = get(userId, type);
|
||||
// if (activity != null) {
|
||||
// if (!activity.isReceived()) {
|
||||
// double totalMoney = activity.getTotalMoney();
|
||||
// int people = activity.getPeople();
|
||||
// double totalReward = 0;
|
||||
// for (RebateRulesSalary rules : activity.getRlist()) {
|
||||
// if (totalMoney >= rules.getMoney()
|
||||
// && people >= rules.getPeople()) {
|
||||
// if (rules.getReward() > totalReward) {
|
||||
// totalReward = rules.getReward();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// if (totalReward > 0) {
|
||||
// User uBean = uDao.getById(userId);
|
||||
// if (uBean != null) {
|
||||
// Moment thisTime = new Moment();
|
||||
// Moment lastTime = new Moment().subtract(1, "days");
|
||||
// ActivitySalaryBill entity = new ActivitySalaryBill(
|
||||
// userId, type, totalMoney, totalReward,
|
||||
// lastTime.toSimpleDate(),
|
||||
// thisTime.toSimpleTime());
|
||||
// boolean bFlag = aSalaryBillDao.add(entity);
|
||||
// if (bFlag) {
|
||||
// boolean uFlag = uDao.updateLotteryMoney(
|
||||
// uBean.getId(), totalReward);
|
||||
// if (uFlag) {
|
||||
// if (type == 1) {
|
||||
// String remarks = "直属日工资活动。";
|
||||
// Integer refType = 1; // 其他活动类型
|
||||
// uBillService.addActivityBill(uBean,
|
||||
// Global.BILL_ACCOUNT_LOTTERY,
|
||||
// totalReward, refType, remarks);
|
||||
// }
|
||||
// if (type == 2) {
|
||||
// String remarks = "总代日工资活动。";
|
||||
// Integer refType = 1; // 其他活动类型
|
||||
// uBillService.addActivityBill(uBean,
|
||||
// Global.BILL_ACCOUNT_LOTTERY,
|
||||
// totalReward, refType, remarks);
|
||||
// }
|
||||
// }
|
||||
// return uFlag;
|
||||
// }
|
||||
// }
|
||||
// } else {
|
||||
// json.set(2, "2-4006");
|
||||
// }
|
||||
// } else {
|
||||
// json.set(2, "2-4005");
|
||||
// }
|
||||
// } else {
|
||||
// json.set(2, "2-4002");
|
||||
// }
|
||||
// return false;
|
||||
// }
|
||||
//
|
||||
// }
|
||||
+256
@@ -0,0 +1,256 @@
|
||||
package activity.domains.content.biz.impl;
|
||||
|
||||
import activity.domains.content.biz.ActivitySignService;
|
||||
import activity.domains.content.dao.ActivitySignBillDao;
|
||||
import activity.domains.content.dao.ActivitySignRecordDao;
|
||||
import activity.domains.content.entity.ActivitySignBill;
|
||||
import activity.domains.content.entity.ActivitySignRecord;
|
||||
import activity.domains.content.vo.activity.ActivitySignVO;
|
||||
import javautils.date.DateUtil;
|
||||
import javautils.date.Moment;
|
||||
import javautils.math.MathUtil;
|
||||
import lottery.domains.content.biz.UserBillService;
|
||||
import lottery.domains.content.biz.read.UserLotteryReportReadService;
|
||||
import lottery.domains.content.dao.UserDao;
|
||||
import lottery.domains.content.entity.User;
|
||||
import lottery.domains.content.global.Global;
|
||||
import lottery.domains.pool.DataFactory;
|
||||
import lottery.web.WebJSON;
|
||||
import org.apache.commons.collections.CollectionUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class ActivitySignServiceImpl implements ActivitySignService {
|
||||
@Autowired
|
||||
private UserDao uDao;
|
||||
|
||||
@Autowired
|
||||
private ActivitySignRecordDao aSignRecordDao;
|
||||
|
||||
@Autowired
|
||||
private ActivitySignBillDao aSignBillDao;
|
||||
|
||||
@Autowired
|
||||
private UserBillService uBillService;
|
||||
|
||||
@Autowired
|
||||
private UserLotteryReportReadService uLotteryReportReadService;
|
||||
|
||||
@Autowired
|
||||
private DataFactory dataFactory;
|
||||
|
||||
/**
|
||||
* 获取签到情况
|
||||
*/
|
||||
@Override
|
||||
public ActivitySignVO getSignData(int userId) {
|
||||
// 活动未开启
|
||||
if (dataFactory.getActivitySignConfig().getStatus() != 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ActivitySignRecord record = aSignRecordDao.getByUserId(userId);
|
||||
|
||||
// 还没有签到过
|
||||
if (record == null) {
|
||||
return new ActivitySignVO(0, false);
|
||||
}
|
||||
|
||||
// 上次签到是否已经中断
|
||||
boolean isInterrupted = isInterrupted(record);
|
||||
if (isInterrupted) {
|
||||
return new ActivitySignVO(0, false);
|
||||
}
|
||||
|
||||
boolean isTodaySigned = isTodaySigned(record);
|
||||
|
||||
if (record.getDays() >= dataFactory.getActivitySignConfig().getDay() && isTodaySigned) {
|
||||
return new ActivitySignVO(dataFactory.getActivitySignConfig().getDay(), isTodaySigned);
|
||||
}
|
||||
|
||||
int days = record.getDays() >= dataFactory.getActivitySignConfig().getDay() ? 0 : record.getDays();
|
||||
|
||||
return new ActivitySignVO(days, isTodaySigned);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double sign(WebJSON json, int userId) {
|
||||
// 活动未开启
|
||||
if (dataFactory.getActivitySignConfig().getStatus() != 0) {
|
||||
json.set(2, "2-4001");
|
||||
return -1;
|
||||
}
|
||||
|
||||
ActivitySignRecord record = aSignRecordDao.getByUserId(userId);
|
||||
|
||||
if (record != null) {
|
||||
// 今天已经签到过了
|
||||
boolean isTodaySigned = isTodaySigned(record);
|
||||
if (isTodaySigned) {
|
||||
json.set(2, "2-4029");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// 是否达到最低消费要求
|
||||
double todayCost = getTodayCost(userId);
|
||||
if (todayCost < dataFactory.getActivitySignConfig().getMinCost()) {
|
||||
int minCostInt = new BigDecimal(dataFactory.getActivitySignConfig().getMinCost()).intValue();
|
||||
json.set(2, "2-4009", minCostInt);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 还没有签到过
|
||||
if (record == null) {
|
||||
firstSign(userId);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 签到已经中断,重新开始签到
|
||||
boolean isInterrupted = isInterrupted(record);
|
||||
if (isInterrupted) {
|
||||
String time = new Moment().toSimpleTime();
|
||||
record.setStartTime(time);
|
||||
record.setLastSignTime(time);
|
||||
record.setDays(1);
|
||||
aSignRecordDao.update(record);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 签到已经满了7天了,重新签
|
||||
if (record.getDays() >= dataFactory.getActivitySignConfig().getDay()) {
|
||||
String time = new Moment().toSimpleTime();
|
||||
record.setStartTime(time);
|
||||
record.setLastSignTime(time);
|
||||
record.setDays(1);
|
||||
aSignRecordDao.update(record);
|
||||
return 0;
|
||||
}
|
||||
|
||||
record.setLastSignTime(new Moment().toSimpleTime());
|
||||
record.setDays(record.getDays()+1);
|
||||
aSignRecordDao.update(record);
|
||||
|
||||
// 如果签到前是第7次签到,那么应该加相应的奖励
|
||||
if (record.getDays() == (dataFactory.getActivitySignConfig().getDay())) {
|
||||
double amount = collect(record);
|
||||
if (amount == 0) {
|
||||
return 0;
|
||||
}
|
||||
else {
|
||||
return amount;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private double collect(ActivitySignRecord record) {
|
||||
String startDate = new Moment().subtract(dataFactory.getActivitySignConfig().getDay()-1, "days").toSimpleDate();
|
||||
String endDate = new Moment().add(1, "days").toSimpleDate();
|
||||
double cost = getCost(record.getUserId(), startDate, endDate);
|
||||
if (cost > dataFactory.getActivitySignConfig().getMinCost()) {
|
||||
double amount = MathUtil.multiply(cost, dataFactory.getActivitySignConfig().getRewardPercent());
|
||||
if (amount > dataFactory.getActivitySignConfig().getMax()) {
|
||||
amount = dataFactory.getActivitySignConfig().getMax();
|
||||
}
|
||||
|
||||
User user = new User();
|
||||
user.setId(record.getUserId());
|
||||
// 新增账单
|
||||
boolean addedBill = uBillService.addActivityBill(user, Global.BILL_ACCOUNT_LOTTERY, amount, Global.BILL_TYPE_ACTIVITY, "签到活动");
|
||||
if (addedBill) {
|
||||
|
||||
// 新增签到账单
|
||||
ActivitySignBill bill = new ActivitySignBill();
|
||||
bill.setDays(record.getDays());
|
||||
bill.setStartTime(record.getStartTime());
|
||||
bill.setEndTime(new Moment().toSimpleTime());
|
||||
bill.setMoney(amount);
|
||||
bill.setScale(dataFactory.getActivitySignConfig().getRewardPercent());
|
||||
bill.setTime(new Moment().toSimpleTime());
|
||||
bill.setTotalCost(cost);
|
||||
bill.setUserId(record.getUserId());
|
||||
aSignBillDao.add(bill);
|
||||
|
||||
// 加钱
|
||||
uDao.updateLotteryMoney(record.getUserId(), amount);
|
||||
|
||||
aSignRecordDao.updateLastCollectTime(record.getUserId(), new Moment().toSimpleTime());
|
||||
}
|
||||
|
||||
return amount;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private int firstSign(int userId) {
|
||||
int days = 1;
|
||||
ActivitySignRecord record = new ActivitySignRecord();
|
||||
record.setUserId(userId);
|
||||
record.setDays(days);
|
||||
String time = new Moment().toSimpleTime();
|
||||
record.setLastSignTime(time);
|
||||
record.setStartTime(time);
|
||||
aSignRecordDao.add(record);
|
||||
return days;
|
||||
}
|
||||
|
||||
/**
|
||||
* 签到过程是否中断
|
||||
*/
|
||||
private boolean isInterrupted(ActivitySignRecord record) {
|
||||
// 上次签到是否已经中断,上次签到时间距离现在超过2天,即已经中断
|
||||
Date lastSignTime = new Moment().fromTime(record.getLastSignTime()).toDate();
|
||||
Date now = new Date();
|
||||
int days = DateUtil.calcDays(now, lastSignTime);
|
||||
if (days >= 2) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 今天是否已经签到
|
||||
*/
|
||||
private boolean isTodaySigned(ActivitySignRecord record) {
|
||||
// 今天是否已经签到
|
||||
if (record == null) return false;
|
||||
|
||||
String lastSignDate = new Moment().fromTime(record.getLastSignTime()).toSimpleDate();
|
||||
String today = new Moment().toSimpleDate();
|
||||
if (today.equals(lastSignDate)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取今天的消费总计
|
||||
*/
|
||||
private double getTodayCost(int userId) {
|
||||
String sDate = new Moment().toSimpleDate();
|
||||
String eDate = new Moment().add(1, "days").toSimpleDate();
|
||||
|
||||
return getCost(userId, sDate, eDate);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取签到期间的消费总计
|
||||
*/
|
||||
private double getCost(int userId, String sDate, String eDate) {
|
||||
List<?> userCosts = uLotteryReportReadService.listAmountGroupByUserIds(new Integer[]{userId}, sDate, eDate);
|
||||
if (CollectionUtils.isNotEmpty(userCosts)) {
|
||||
Object[] userCostArr = (Object[]) userCosts.get(0);
|
||||
double cost = (Double) userCostArr[1];
|
||||
return cost;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package activity.domains.content.dao;
|
||||
|
||||
|
||||
public interface ActivityBindBillDao {
|
||||
|
||||
//boolean add(ActivityBindBill entity);
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package activity.domains.content.dao;
|
||||
|
||||
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.hibernate.criterion.Criterion;
|
||||
import org.hibernate.criterion.Order;
|
||||
|
||||
import activity.domains.content.entity.ActivityCostBill;
|
||||
import javautils.jdbc.PageList;
|
||||
|
||||
public interface ActivityCostBillDao {
|
||||
|
||||
ActivityCostBill getDrawInfo(int user,String statrTime,String endTme);
|
||||
|
||||
PageList search(List<Criterion> criterions, List<Order> orders, int start, int limit);
|
||||
|
||||
boolean add(ActivityCostBill bill);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package activity.domains.content.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import activity.domains.content.entity.ActivityRebate;
|
||||
|
||||
public interface ActivityRebateDao {
|
||||
|
||||
boolean add(ActivityRebate entity);
|
||||
|
||||
ActivityRebate getById(int id);
|
||||
|
||||
ActivityRebate getByType(int type);
|
||||
|
||||
ActivityRebate getByStatusAndType(int type,int status);
|
||||
|
||||
List<ActivityRebate>getList(int status);
|
||||
|
||||
boolean update(ActivityRebate entity);
|
||||
|
||||
|
||||
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package activity.domains.content.dao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import activity.domains.content.entity.ActivityRechargeLoopBill;
|
||||
|
||||
public interface ActivityRechargeLoopBillDao {
|
||||
|
||||
boolean add(ActivityRechargeLoopBill entity);
|
||||
|
||||
List<ActivityRechargeLoopBill> getByDate(int userId, String date);
|
||||
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package activity.domains.content.dao;
|
||||
|
||||
import activity.domains.content.entity.ActivitySalaryBill;
|
||||
|
||||
public interface ActivitySalaryBillDao {
|
||||
|
||||
boolean add(ActivitySalaryBill entity);
|
||||
|
||||
boolean hasRecord(int userId, int type, String date);
|
||||
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package activity.domains.content.dao;
|
||||
|
||||
import activity.domains.content.entity.ActivitySignBill;
|
||||
|
||||
public interface ActivitySignBillDao {
|
||||
|
||||
boolean add(ActivitySignBill entity);
|
||||
|
||||
ActivitySignBill get(int userId, String time);
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package activity.domains.content.dao;
|
||||
|
||||
import activity.domains.content.entity.ActivitySignRecord;
|
||||
|
||||
public interface ActivitySignRecordDao {
|
||||
boolean add(ActivitySignRecord entity);
|
||||
|
||||
boolean update(ActivitySignRecord entity);
|
||||
|
||||
boolean updateLastCollectTime(int userId, String time);
|
||||
|
||||
boolean delete(int userId);
|
||||
|
||||
ActivitySignRecord getByUserId(int userId);
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package activity.domains.content.dao.impl;
|
||||
|
||||
import activity.domains.content.dao.ActivityBindBillDao;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class ActivityBindBillDaoImpl implements ActivityBindBillDao {
|
||||
|
||||
// @Autowired
|
||||
// private HibernateSuperDao<ActivityBindBill> superDao;
|
||||
|
||||
// @Override
|
||||
// public boolean add(ActivityBindBill entity) {
|
||||
// return superDao.save(entity);
|
||||
// }
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package activity.domains.content.dao.impl;
|
||||
|
||||
|
||||
import activity.domains.content.dao.ActivityCostBillDao;
|
||||
import activity.domains.content.entity.ActivityCostBill;
|
||||
import javautils.jdbc.PageList;
|
||||
import javautils.jdbc.hibernate.HibernateSuperDao;
|
||||
import org.hibernate.criterion.Criterion;
|
||||
import org.hibernate.criterion.Order;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
@Repository
|
||||
public class ActivityCostBillDaoImpl implements ActivityCostBillDao {
|
||||
private final String tab = ActivityCostBill.class.getSimpleName();
|
||||
|
||||
@Autowired
|
||||
private HibernateSuperDao<ActivityCostBill> superDao;
|
||||
|
||||
@Override
|
||||
public ActivityCostBill getDrawInfo(int userId, String sTime, String eTime) {
|
||||
String hql = "from " + tab + " where userId= ?0 and time >= ?1 and time <= ?2";
|
||||
Object[] values = {userId,sTime, eTime};
|
||||
Object result = superDao.unique(hql, values);
|
||||
return (ActivityCostBill) result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageList search(List<Criterion> criterions, List<Order> orders, int start, int limit) {
|
||||
// String hql = " from " + tab + " where userId = ?0 order by time desc limit 1";
|
||||
// Object[] values = {userId};
|
||||
// Object result = superDao.unique(hql, values);
|
||||
// return (ActivityCostBill) result;
|
||||
String propertyName = "id";
|
||||
return superDao.findPageList(ActivityCostBill.class, propertyName, criterions, orders, start, limit);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public boolean add(ActivityCostBill entity) {
|
||||
return superDao.save(entity);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package activity.domains.content.dao.impl;
|
||||
|
||||
import activity.domains.content.dao.ActivityRebateDao;
|
||||
import activity.domains.content.entity.ActivityRebate;
|
||||
import javautils.jdbc.hibernate.HibernateSuperDao;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class ActivityRebateDaoImpl implements ActivityRebateDao {
|
||||
|
||||
private final String tab = ActivityRebate.class.getSimpleName();
|
||||
|
||||
@Autowired
|
||||
private HibernateSuperDao<ActivityRebate> superDao;
|
||||
|
||||
@Override
|
||||
public boolean add(ActivityRebate entity) {
|
||||
return superDao.save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActivityRebate getById(int id) {
|
||||
String hql = "from " + tab + " where id = ?0";
|
||||
Object[] values = { id };
|
||||
return (ActivityRebate) superDao.unique(hql, values);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActivityRebate getByType(int type) {
|
||||
String hql = "from " + tab + " where type = ?0";
|
||||
Object[] values = { type };
|
||||
return (ActivityRebate) superDao.unique(hql, values);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean update(ActivityRebate entity) {
|
||||
return superDao.update(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActivityRebate getByStatusAndType(int type, int status) {
|
||||
String hql = "from " + tab + " where type = ?0 and status =?1";
|
||||
Object[] values = { type ,status};
|
||||
return (ActivityRebate) superDao.unique(hql, values);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ActivityRebate> getList(int status) {
|
||||
String hql = "from " + tab + " where status = ?0 ";
|
||||
Object[] values = {status};
|
||||
return superDao.list(hql, values);
|
||||
}
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package activity.domains.content.dao.impl;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import activity.domains.content.dao.ActivityRechargeLoopBillDao;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import activity.domains.content.entity.ActivityRechargeLoopBill;
|
||||
import javautils.jdbc.hibernate.HibernateSuperDao;
|
||||
|
||||
@Repository
|
||||
public class ActivityRechargeLoopBillDaoImpl implements ActivityRechargeLoopBillDao {
|
||||
|
||||
private final String tab = ActivityRechargeLoopBill.class.getSimpleName();
|
||||
|
||||
@Autowired
|
||||
private HibernateSuperDao<ActivityRechargeLoopBill> superDao;
|
||||
|
||||
@Override
|
||||
public boolean add(ActivityRechargeLoopBill entity) {
|
||||
return superDao.save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ActivityRechargeLoopBill> getByDate(int userId, String date) {
|
||||
String hql = "from " + tab + " where userId = ?0 and time like ?1";
|
||||
Object[] values = {userId, "%" + date + "%"};
|
||||
return superDao.list(hql, values);
|
||||
}
|
||||
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package activity.domains.content.dao.impl;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import activity.domains.content.dao.ActivitySalaryBillDao;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import activity.domains.content.entity.ActivitySalaryBill;
|
||||
import javautils.jdbc.hibernate.HibernateSuperDao;
|
||||
|
||||
@Repository
|
||||
public class ActivitySalaryBillDaoImpl implements ActivitySalaryBillDao {
|
||||
|
||||
private final String tab = ActivitySalaryBill.class.getSimpleName();
|
||||
|
||||
@Autowired
|
||||
private HibernateSuperDao<ActivitySalaryBill> superDao;
|
||||
|
||||
@Override
|
||||
public boolean add(ActivitySalaryBill entity) {
|
||||
return superDao.save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasRecord(int userId, int type, String date) {
|
||||
String hql = "from " + tab + " where userId = ?0 and type = ?1 and date = ?2";
|
||||
Object[] values = {userId, type, date};
|
||||
List<ActivitySalaryBill> list = superDao.list(hql, values);
|
||||
if(list != null && list.size() > 0) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package activity.domains.content.dao.impl;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import activity.domains.content.dao.ActivitySignBillDao;
|
||||
import javautils.jdbc.hibernate.HibernateSuperDao;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import activity.domains.content.entity.ActivitySignBill;
|
||||
|
||||
@Repository
|
||||
public class ActivitySignBillDaoImpl implements ActivitySignBillDao {
|
||||
|
||||
private final String tab = ActivitySignBill.class.getSimpleName();
|
||||
|
||||
@Autowired
|
||||
private HibernateSuperDao<ActivitySignBill> superDao;
|
||||
|
||||
@Override
|
||||
public boolean add(ActivitySignBill entity) {
|
||||
return superDao.save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActivitySignBill get(int userId, String time) {
|
||||
String hql = "from " + tab + " where userId = ?0 and time like ?1";
|
||||
Object[] values = {userId, "%" + time + "%"};
|
||||
List<ActivitySignBill> list = superDao.list(hql, values);
|
||||
if(list != null && list.size() > 0) {
|
||||
return list.get(0);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package activity.domains.content.dao.impl;
|
||||
|
||||
import activity.domains.content.dao.ActivitySignRecordDao;
|
||||
import activity.domains.content.entity.ActivitySignRecord;
|
||||
import javautils.jdbc.hibernate.HibernateSuperDao;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class ActivitySignRecordDaoImpl implements ActivitySignRecordDao {
|
||||
|
||||
private final String tab = ActivitySignRecord.class.getSimpleName();
|
||||
|
||||
@Autowired
|
||||
private HibernateSuperDao<ActivitySignRecord> superDao;
|
||||
|
||||
@Override
|
||||
public boolean add(ActivitySignRecord entity) {
|
||||
return superDao.save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean update(ActivitySignRecord entity) {
|
||||
return superDao.update(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateLastCollectTime(int userId, String time) {
|
||||
String hql = "update " + tab + " set lastCollectTime = ?0 where userId = ?1";
|
||||
Object[] values = { time, userId };
|
||||
return superDao.update(hql, values);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ActivitySignRecord getByUserId(int userId) {
|
||||
String hql = "from " + tab + " where userId = ?0";
|
||||
Object[] values = {userId};
|
||||
return (ActivitySignRecord) superDao.unique(hql, values);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean delete(int userId) {
|
||||
String hql = "deleteAllByUpUserId from " + tab + " where userId = ?0";
|
||||
Object[] values = {userId};
|
||||
return superDao.delete(hql, values);
|
||||
}
|
||||
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package activity.domains.content.entity;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import static javax.persistence.GenerationType.IDENTITY;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import lottery.domains.content.global.Database;
|
||||
|
||||
/**
|
||||
* ActivityBindBill entity. @author MyEclipse Persistence Tools
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "activity_bind_bill", catalog = Database.name)
|
||||
public class ActivityBindBill implements java.io.Serializable {
|
||||
|
||||
// Fields
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
private int id;
|
||||
private int userId;
|
||||
private String registTime;
|
||||
private String ip;
|
||||
private String bindName;
|
||||
private int bindBank;
|
||||
private String bindCard;
|
||||
private double money;
|
||||
private String time;
|
||||
private int status;
|
||||
|
||||
// Constructors
|
||||
|
||||
/** default constructor */
|
||||
public ActivityBindBill() {
|
||||
}
|
||||
|
||||
/** full constructor */
|
||||
public ActivityBindBill(int userId, String registTime, String ip,
|
||||
String bindName, int bindBank, String bindCard,
|
||||
double money, String time, int status) {
|
||||
this.userId = userId;
|
||||
this.registTime = registTime;
|
||||
this.ip = ip;
|
||||
this.bindName = bindName;
|
||||
this.bindBank = bindBank;
|
||||
this.bindCard = bindCard;
|
||||
this.money = money;
|
||||
this.time = time;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
// Property accessors
|
||||
@Id
|
||||
@GeneratedValue(strategy = IDENTITY)
|
||||
@Column(name = "id", unique = true, nullable = false)
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
public int getUserId() {
|
||||
return this.userId;
|
||||
}
|
||||
|
||||
public void setUserId(int userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
@Column(name = "regist_time", nullable = false, length = 19)
|
||||
public String getRegistTime() {
|
||||
return this.registTime;
|
||||
}
|
||||
|
||||
public void setRegistTime(String registTime) {
|
||||
this.registTime = registTime;
|
||||
}
|
||||
|
||||
@Column(name = "ip", nullable = false, length = 128)
|
||||
public String getIp() {
|
||||
return this.ip;
|
||||
}
|
||||
|
||||
public void setIp(String ip) {
|
||||
this.ip = ip;
|
||||
}
|
||||
|
||||
@Column(name = "bind_name", nullable = false, length = 64)
|
||||
public String getBindName() {
|
||||
return this.bindName;
|
||||
}
|
||||
|
||||
public void setBindName(String bindName) {
|
||||
this.bindName = bindName;
|
||||
}
|
||||
|
||||
@Column(name = "bind_bank", nullable = false)
|
||||
public int getBindBank() {
|
||||
return this.bindBank;
|
||||
}
|
||||
|
||||
public void setBindBank(int bindBank) {
|
||||
this.bindBank = bindBank;
|
||||
}
|
||||
|
||||
@Column(name = "bind_card", nullable = false, length = 128)
|
||||
public String getBindCard() {
|
||||
return this.bindCard;
|
||||
}
|
||||
|
||||
public void setBindCard(String bindCard) {
|
||||
this.bindCard = bindCard;
|
||||
}
|
||||
|
||||
@Column(name = "money", nullable = false, precision = 16, scale = 5)
|
||||
public double getMoney() {
|
||||
return this.money;
|
||||
}
|
||||
|
||||
public void setMoney(double money) {
|
||||
this.money = money;
|
||||
}
|
||||
|
||||
@Column(name = "time", nullable = false, length = 19)
|
||||
public String getTime() {
|
||||
return this.time;
|
||||
}
|
||||
|
||||
public void setTime(String time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
@Column(name = "status", nullable = false)
|
||||
public int getStatus() {
|
||||
return this.status;
|
||||
}
|
||||
|
||||
public void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package activity.domains.content.entity;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
|
||||
import static javax.persistence.GenerationType.IDENTITY;
|
||||
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import lottery.domains.content.global.Database;
|
||||
|
||||
/**
|
||||
* activity_cost_bill entity. @author MyEclipse Persistence Tools
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "activity_cost_bill", catalog = Database.name)
|
||||
public class ActivityCostBill implements java.io.Serializable {
|
||||
|
||||
// Fields
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
private int id;
|
||||
private int userId;
|
||||
private double totalCost;
|
||||
private double money;
|
||||
private String time;
|
||||
private String drawIp;
|
||||
|
||||
// Constructors
|
||||
|
||||
/** default constructor */
|
||||
public ActivityCostBill() {
|
||||
}
|
||||
|
||||
/** full constructor */
|
||||
public ActivityCostBill(int id,int userId, double totalCost, double money,
|
||||
String time,String drawIp) {
|
||||
this.id = id;
|
||||
this.userId = userId;
|
||||
this.totalCost = totalCost;
|
||||
this.money = money;
|
||||
this.time = time;
|
||||
this.drawIp = drawIp;
|
||||
}
|
||||
|
||||
public ActivityCostBill(int userId, double totalCost, double money,
|
||||
String time,String drawIp) {
|
||||
this.userId = userId;
|
||||
this.totalCost = totalCost;
|
||||
this.money = money;
|
||||
this.time = time;
|
||||
this.drawIp = drawIp;
|
||||
}
|
||||
|
||||
// Property accessors
|
||||
@Id
|
||||
@GeneratedValue(strategy = IDENTITY)
|
||||
@Column(name = "id", unique = true, nullable = false)
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
public int getUserId() {
|
||||
return this.userId;
|
||||
}
|
||||
|
||||
public void setUserId(int userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
@Column(name = "total_cost", nullable = false, precision = 16, scale = 5)
|
||||
public double getTotalCost() {
|
||||
return this.totalCost;
|
||||
}
|
||||
|
||||
public void setTotalCost(double totalCost) {
|
||||
this.totalCost = totalCost;
|
||||
}
|
||||
|
||||
@Column(name = "money", nullable = false, precision = 16, scale = 5)
|
||||
public double getMoney() {
|
||||
return this.money;
|
||||
}
|
||||
|
||||
public void setMoney(double money) {
|
||||
this.money = money;
|
||||
}
|
||||
|
||||
@Column(name = "time", nullable = false, length = 19)
|
||||
public String getTime() {
|
||||
return this.time;
|
||||
}
|
||||
|
||||
public void setTime(String time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
@Column(name = "draw_ip", nullable = false, length = 30)
|
||||
public String getDrawIp() {
|
||||
return drawIp;
|
||||
}
|
||||
|
||||
public void setDrawIp(String drawIp) {
|
||||
this.drawIp = drawIp;
|
||||
}
|
||||
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package activity.domains.content.entity;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
|
||||
import static javax.persistence.GenerationType.IDENTITY;
|
||||
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import lottery.domains.content.global.Database;
|
||||
|
||||
/**
|
||||
* ActivitySignBill entity. @author MyEclipse Persistence Tools
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "activity_packet_bill", catalog = Database.name)
|
||||
public class ActivityPacketBill implements java.io.Serializable {
|
||||
|
||||
// Fields
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
private int id;
|
||||
private int userId;
|
||||
private String time;
|
||||
private int packetId;
|
||||
private double amount;
|
||||
private int status;//0初始状态1被抢状态
|
||||
private double cost;
|
||||
private String ip;
|
||||
|
||||
|
||||
// Constructors
|
||||
|
||||
@Column(name = "ip")
|
||||
public String getIp() {
|
||||
return ip;
|
||||
}
|
||||
|
||||
public void setIp(String ip) {
|
||||
this.ip = ip;
|
||||
}
|
||||
|
||||
|
||||
@Column(name = "cost")
|
||||
public double getCost() {
|
||||
return cost;
|
||||
}
|
||||
|
||||
public void setCost(double cost) {
|
||||
this.cost = cost;
|
||||
}
|
||||
|
||||
@Column(name = "packet_id", nullable = false)
|
||||
public int getPacketId() {
|
||||
return packetId;
|
||||
}
|
||||
|
||||
public void setPacketId(int packetId) {
|
||||
this.packetId = packetId;
|
||||
}
|
||||
|
||||
@Column(name = "amount", nullable = false)
|
||||
public double getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(double amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
@Column(name = "status", nullable = false)
|
||||
public int getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
/** default constructor */
|
||||
public ActivityPacketBill() {
|
||||
}
|
||||
|
||||
/** full constructor */
|
||||
|
||||
// Property accessors
|
||||
@Id
|
||||
@GeneratedValue(strategy = IDENTITY)
|
||||
@Column(name = "id", unique = true, nullable = false)
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
public int getUserId() {
|
||||
return this.userId;
|
||||
}
|
||||
|
||||
public void setUserId(int userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
@Column(name = "time", length = 19)
|
||||
public String getTime() {
|
||||
return this.time;
|
||||
}
|
||||
|
||||
public void setTime(String time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
// package activity.domains.content.entity;
|
||||
//
|
||||
// import java.util.List;
|
||||
// import java.util.concurrent.TimeUnit;
|
||||
//
|
||||
// import javax.persistence.Column;
|
||||
// import javax.persistence.Entity;
|
||||
// import javax.persistence.GeneratedValue;
|
||||
//
|
||||
// import static javax.persistence.GenerationType.IDENTITY;
|
||||
//
|
||||
// import javax.persistence.Id;
|
||||
// import javax.persistence.Table;
|
||||
//
|
||||
// import lottery.domains.content.dao.ActivityPacketBillWriteDao;
|
||||
// import lottery.domains.content.global.Database;
|
||||
//
|
||||
// /**
|
||||
// * ActivitySignBill entity. @author MyEclipse Persistence Tools
|
||||
// */
|
||||
// @Entity
|
||||
// @Table(name = "activity_packet_info", catalog = Database.name)
|
||||
// public class ActivityPacketInfo implements java.io.Serializable {
|
||||
//
|
||||
// // Fields
|
||||
//
|
||||
// /**
|
||||
// *
|
||||
// */
|
||||
// private static final long serialVersionUID = 1L;
|
||||
// private int id;
|
||||
// private int userId;
|
||||
// private String time;
|
||||
// private double amount;
|
||||
// private int count;
|
||||
// private int type;//红包类型0:系统红包 1:用户红包
|
||||
// private int status;//红包状态 0可抢状态 1已抢完
|
||||
//
|
||||
// private static final String CACHE_PREFIX_PB = "_packet_bills_";//可用红包cache前缀
|
||||
//
|
||||
// private static final int CACHE_EXPIRE_SECONDS = 60 * 10;//cache过期时间
|
||||
//
|
||||
// public enum PacketType{
|
||||
// SYSTEM_PACKET(0),//"系统红包"
|
||||
// USER_PACKET(1);//"用户红包"
|
||||
//
|
||||
// private Integer type;
|
||||
//
|
||||
// private PacketType(int type){
|
||||
// this.type = type;
|
||||
// }
|
||||
//
|
||||
// public int get(){
|
||||
// return this.type;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public enum PacketStatus{
|
||||
// AVALIABLE(0),//"可抢状态"
|
||||
// FINISH(1);//"已抢完
|
||||
//
|
||||
// private Integer status;
|
||||
//
|
||||
// private PacketStatus(int status){
|
||||
// this.status = status;
|
||||
// }
|
||||
//
|
||||
// public int get(){
|
||||
// return this.status;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // Constructors
|
||||
//
|
||||
// /** default constructor */
|
||||
// public ActivityPacketInfo() {
|
||||
// }
|
||||
//
|
||||
// /** full constructor */
|
||||
//
|
||||
//
|
||||
// // Property accessors
|
||||
// @Id
|
||||
// @GeneratedValue(strategy = IDENTITY)
|
||||
// @Column(name = "id", unique = true, nullable = false)
|
||||
// public int getId() {
|
||||
// return this.id;
|
||||
// }
|
||||
//
|
||||
// public void setId(int id) {
|
||||
// this.id = id;
|
||||
// }
|
||||
//
|
||||
// @Column(name = "user_id", nullable = false)
|
||||
// public int getUserId() {
|
||||
// return this.userId;
|
||||
// }
|
||||
//
|
||||
// public void setUserId(int userId) {
|
||||
// this.userId = userId;
|
||||
// }
|
||||
//
|
||||
// @Column(name = "amount", nullable = false)
|
||||
// public double getAmount() {
|
||||
// return amount;
|
||||
// }
|
||||
//
|
||||
// public void setAmount(double amount) {
|
||||
// this.amount = amount;
|
||||
// }
|
||||
//
|
||||
// @Column(name = "count", nullable = false)
|
||||
// public int getCount() {
|
||||
// return count;
|
||||
// }
|
||||
//
|
||||
// public void setCount(int count) {
|
||||
// this.count = count;
|
||||
// }
|
||||
//
|
||||
// @Column(name = "type", nullable = false)
|
||||
// public int getType() {
|
||||
// return type;
|
||||
// }
|
||||
//
|
||||
// public void setType(int type) {
|
||||
// this.type = type;
|
||||
// }
|
||||
//
|
||||
// @Column(name = "status", nullable = false)
|
||||
// public int getStatus() {
|
||||
// return status;
|
||||
// }
|
||||
//
|
||||
// public void setStatus(int status) {
|
||||
// this.status = status;
|
||||
// }
|
||||
//
|
||||
// @Column(name = "time", nullable = false, length = 19)
|
||||
// public String getTime() {
|
||||
// return this.time;
|
||||
// }
|
||||
//
|
||||
// public void setTime(String time) {
|
||||
// this.time = time;
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 获取一个红包小面的所有份数对象
|
||||
// * @param dao
|
||||
// * @param redis
|
||||
// * @param useCache
|
||||
// * 是否使用缓存
|
||||
// * @return
|
||||
// */
|
||||
// @SuppressWarnings("unchecked")
|
||||
// public List<ActivityPacketBill> getPackets(ActivityPacketBillWriteDao dao, RedisTemplate<String, Object> redis, boolean useCache){
|
||||
// if(useCache){
|
||||
// List<ActivityPacketBill> cPackets = (List<ActivityPacketBill>) redis.opsForValue().get(CACHE_PREFIX_PB + this.getId());
|
||||
// if(cPackets == null){
|
||||
// return getPackets(dao, redis, false);
|
||||
// }else{
|
||||
// return cPackets;
|
||||
// }
|
||||
// }else{
|
||||
// List<ActivityPacketBill> packets = dao.findByPacketId(this.getId());
|
||||
// if(packets != null && !packets.isEmpty()){
|
||||
// redis.opsForValue().set(CACHE_PREFIX_PB + this.getId(), packets);
|
||||
// redis.expire(CACHE_PREFIX_PB + this.getId(), CACHE_EXPIRE_SECONDS, TimeUnit.SECONDS);
|
||||
// }
|
||||
// return packets;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 更新缓存
|
||||
// * @param redis
|
||||
// * @param cList
|
||||
// */
|
||||
// public void refreshCache(RedisTemplate<String, Object> redis, List<ActivityPacketBill> cList){
|
||||
// redis.opsForValue().set(CACHE_PREFIX_PB + this.getId(), cList);
|
||||
// redis.expire(CACHE_PREFIX_PB + this.getId(), CACHE_EXPIRE_SECONDS, TimeUnit.SECONDS);
|
||||
// }
|
||||
//
|
||||
// public void deleteCache(RedisTemplate<String, Object> redis){
|
||||
// redis.deleteAllByUpUserId(CACHE_PREFIX_PB + this.getId());
|
||||
// }
|
||||
// }
|
||||
@@ -0,0 +1,114 @@
|
||||
package activity.domains.content.entity;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
|
||||
import static javax.persistence.GenerationType.IDENTITY;
|
||||
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import lottery.domains.content.global.Database;
|
||||
|
||||
/**
|
||||
* ActivityRebate entity. @author MyEclipse Persistence Tools
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "activity_rebate", catalog = Database.name)
|
||||
public class ActivityRebate implements java.io.Serializable {
|
||||
|
||||
// Fields
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
private int id;
|
||||
private int type;
|
||||
private String rules;
|
||||
private String startTime;
|
||||
private String endTime;
|
||||
private int status;
|
||||
|
||||
// Constructors
|
||||
|
||||
/** default constructor */
|
||||
public ActivityRebate() {
|
||||
}
|
||||
|
||||
/** minimal constructor */
|
||||
public ActivityRebate(int type, String rules, int status) {
|
||||
this.type = type;
|
||||
this.rules = rules;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
/** full constructor */
|
||||
public ActivityRebate(int type, String rules, String startTime,
|
||||
String endTime, int status) {
|
||||
this.type = type;
|
||||
this.rules = rules;
|
||||
this.startTime = startTime;
|
||||
this.endTime = endTime;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
// Property accessors
|
||||
@Id
|
||||
@GeneratedValue(strategy = IDENTITY)
|
||||
@Column(name = "id", unique = true, nullable = false)
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Column(name = "type", nullable = false)
|
||||
public int getType() {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
public void setType(int type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@Column(name = "rules", nullable = false, length = 65535)
|
||||
public String getRules() {
|
||||
return this.rules;
|
||||
}
|
||||
|
||||
public void setRules(String rules) {
|
||||
this.rules = rules;
|
||||
}
|
||||
|
||||
@Column(name = "startTime")
|
||||
public String getStartTime() {
|
||||
return this.startTime;
|
||||
}
|
||||
|
||||
public void setStartTime(String startTime) {
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
@Column(name = "endTime")
|
||||
public String getEndTime() {
|
||||
return this.endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(String endTime) {
|
||||
this.endTime = endTime;
|
||||
}
|
||||
|
||||
@Column(name = "status", nullable = false)
|
||||
public int getStatus() {
|
||||
return this.status;
|
||||
}
|
||||
|
||||
public void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package activity.domains.content.entity;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import static javax.persistence.GenerationType.IDENTITY;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import lottery.domains.content.global.Database;
|
||||
|
||||
/**
|
||||
* ActivityRechargeLoopBill entity. @author MyEclipse Persistence Tools
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "activity_recharge_loop_bill", catalog = Database.name)
|
||||
public class ActivityRechargeLoopBill implements java.io.Serializable {
|
||||
|
||||
// Fields
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
private int id;
|
||||
private int userId;
|
||||
private String ip;
|
||||
private int step;
|
||||
private double totalMoney;
|
||||
private double totalCost;
|
||||
private double money;
|
||||
private String time;
|
||||
|
||||
// Constructors
|
||||
|
||||
/** default constructor */
|
||||
public ActivityRechargeLoopBill() {
|
||||
}
|
||||
|
||||
/** full constructor */
|
||||
public ActivityRechargeLoopBill(int userId, String ip, int step,
|
||||
double totalMoney, double totalCost, double money, String time) {
|
||||
this.userId = userId;
|
||||
this.ip = ip;
|
||||
this.step = step;
|
||||
this.totalMoney = totalMoney;
|
||||
this.totalCost = totalCost;
|
||||
this.money = money;
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
// Property accessors
|
||||
@Id
|
||||
@GeneratedValue(strategy = IDENTITY)
|
||||
@Column(name = "id", unique = true, nullable = false)
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
public int getUserId() {
|
||||
return this.userId;
|
||||
}
|
||||
|
||||
public void setUserId(int userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
@Column(name = "ip", nullable = false, length = 128)
|
||||
public String getIp() {
|
||||
return this.ip;
|
||||
}
|
||||
|
||||
public void setIp(String ip) {
|
||||
this.ip = ip;
|
||||
}
|
||||
|
||||
@Column(name = "step", nullable = false)
|
||||
public int getStep() {
|
||||
return this.step;
|
||||
}
|
||||
|
||||
public void setStep(int step) {
|
||||
this.step = step;
|
||||
}
|
||||
|
||||
@Column(name = "total_money", nullable = false, precision = 16, scale = 5)
|
||||
public double getTotalMoney() {
|
||||
return this.totalMoney;
|
||||
}
|
||||
|
||||
public void setTotalMoney(double totalMoney) {
|
||||
this.totalMoney = totalMoney;
|
||||
}
|
||||
|
||||
@Column(name = "total_cost", nullable = false, precision = 16, scale = 5)
|
||||
public double getTotalCost() {
|
||||
return this.totalCost;
|
||||
}
|
||||
|
||||
public void setTotalCost(double totalCost) {
|
||||
this.totalCost = totalCost;
|
||||
}
|
||||
|
||||
@Column(name = "money", nullable = false, precision = 16, scale = 5)
|
||||
public double getMoney() {
|
||||
return this.money;
|
||||
}
|
||||
|
||||
public void setMoney(double money) {
|
||||
this.money = money;
|
||||
}
|
||||
|
||||
@Column(name = "time", nullable = false, length = 19)
|
||||
public String getTime() {
|
||||
return this.time;
|
||||
}
|
||||
|
||||
public void setTime(String time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package activity.domains.content.entity;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import static javax.persistence.GenerationType.IDENTITY;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import lottery.domains.content.global.Database;
|
||||
|
||||
/**
|
||||
* ActivitySalaryBill entity. @author MyEclipse Persistence Tools
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "activity_salary_bill", catalog = Database.name)
|
||||
public class ActivitySalaryBill implements java.io.Serializable {
|
||||
|
||||
// Fields
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
private int id;
|
||||
private int userId;
|
||||
private int type;
|
||||
private double totalMoney;
|
||||
private double money;
|
||||
private String date;
|
||||
private String time;
|
||||
|
||||
// Constructors
|
||||
|
||||
/** default constructor */
|
||||
public ActivitySalaryBill() {
|
||||
}
|
||||
|
||||
/** full constructor */
|
||||
public ActivitySalaryBill(int userId, int type, double totalMoney, double money, String date, String time) {
|
||||
this.userId = userId;
|
||||
this.type = type;
|
||||
this.totalMoney = totalMoney;
|
||||
this.money = money;
|
||||
this.date = date;
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
// Property accessors
|
||||
@Id
|
||||
@GeneratedValue(strategy = IDENTITY)
|
||||
@Column(name = "id", unique = true, nullable = false)
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
public int getUserId() {
|
||||
return this.userId;
|
||||
}
|
||||
|
||||
public void setUserId(int userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
@Column(name = "type", nullable = false)
|
||||
public int getType() {
|
||||
return this.type;
|
||||
}
|
||||
|
||||
public void setType(int type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
@Column(name = "total_money", nullable = false, precision = 16, scale = 5)
|
||||
public double getTotalMoney() {
|
||||
return this.totalMoney;
|
||||
}
|
||||
|
||||
public void setTotalMoney(double totalMoney) {
|
||||
this.totalMoney = totalMoney;
|
||||
}
|
||||
|
||||
@Column(name = "money", nullable = false, precision = 16, scale = 5)
|
||||
public double getMoney() {
|
||||
return this.money;
|
||||
}
|
||||
|
||||
public void setMoney(double money) {
|
||||
this.money = money;
|
||||
}
|
||||
|
||||
@Column(name = "date", nullable = false, length = 10)
|
||||
public String getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(String date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
@Column(name = "time", nullable = false, length = 19)
|
||||
public String getTime() {
|
||||
return this.time;
|
||||
}
|
||||
|
||||
public void setTime(String time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package activity.domains.content.entity;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
|
||||
import static javax.persistence.GenerationType.IDENTITY;
|
||||
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import lottery.domains.content.global.Database;
|
||||
|
||||
/**
|
||||
* ActivitySignBill entity. @author MyEclipse Persistence Tools
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "activity_sign_bill", catalog = Database.name)
|
||||
public class ActivitySignBill implements java.io.Serializable {
|
||||
|
||||
// Fields
|
||||
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
private int id;
|
||||
private int userId;
|
||||
private int days;
|
||||
private String startTime;
|
||||
private String endTime;
|
||||
private double totalCost;
|
||||
private double scale;
|
||||
private double money;
|
||||
private String time;
|
||||
|
||||
// Constructors
|
||||
|
||||
/** default constructor */
|
||||
public ActivitySignBill() {
|
||||
}
|
||||
|
||||
/** full constructor */
|
||||
public ActivitySignBill(int userId, int days, String startTime,
|
||||
String endTime, double totalCost, double scale, double money,
|
||||
String time) {
|
||||
this.userId = userId;
|
||||
this.days = days;
|
||||
this.startTime = startTime;
|
||||
this.endTime = endTime;
|
||||
this.totalCost = totalCost;
|
||||
this.scale = scale;
|
||||
this.money = money;
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
// Property accessors
|
||||
@Id
|
||||
@GeneratedValue(strategy = IDENTITY)
|
||||
@Column(name = "id", unique = true, nullable = false)
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
public int getUserId() {
|
||||
return this.userId;
|
||||
}
|
||||
|
||||
public void setUserId(int userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
@Column(name = "days", nullable = false)
|
||||
public int getDays() {
|
||||
return this.days;
|
||||
}
|
||||
|
||||
public void setDays(int days) {
|
||||
this.days = days;
|
||||
}
|
||||
|
||||
@Column(name = "start_time", nullable = false, length = 19)
|
||||
public String getStartTime() {
|
||||
return this.startTime;
|
||||
}
|
||||
|
||||
public void setStartTime(String startTime) {
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
@Column(name = "end_time", nullable = false, length = 19)
|
||||
public String getEndTime() {
|
||||
return this.endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(String endTime) {
|
||||
this.endTime = endTime;
|
||||
}
|
||||
|
||||
@Column(name = "total_cost", nullable = false, precision = 16, scale = 5)
|
||||
public double getTotalCost() {
|
||||
return this.totalCost;
|
||||
}
|
||||
|
||||
public void setTotalCost(double totalCost) {
|
||||
this.totalCost = totalCost;
|
||||
}
|
||||
|
||||
@Column(name = "scale", nullable = false, precision = 16, scale = 5)
|
||||
public double getScale() {
|
||||
return this.scale;
|
||||
}
|
||||
|
||||
public void setScale(double scale) {
|
||||
this.scale = scale;
|
||||
}
|
||||
|
||||
@Column(name = "money", nullable = false, precision = 16, scale = 5)
|
||||
public double getMoney() {
|
||||
return this.money;
|
||||
}
|
||||
|
||||
public void setMoney(double money) {
|
||||
this.money = money;
|
||||
}
|
||||
|
||||
@Column(name = "time", nullable = false, length = 19)
|
||||
public String getTime() {
|
||||
return this.time;
|
||||
}
|
||||
|
||||
public void setTime(String time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package activity.domains.content.entity;
|
||||
|
||||
import lottery.domains.content.global.Database;
|
||||
|
||||
import javax.persistence.*;
|
||||
|
||||
import static javax.persistence.GenerationType.IDENTITY;
|
||||
|
||||
/**
|
||||
* ActivitySignRecord entity. @author MyEclipse Persistence Tools
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "activity_sign_record", catalog = Database.name)
|
||||
public class ActivitySignRecord implements java.io.Serializable {
|
||||
private int id;
|
||||
private int userId;
|
||||
private int days;
|
||||
private String startTime;
|
||||
private String lastSignTime;
|
||||
private String lastCollectTime;
|
||||
|
||||
// Constructors
|
||||
|
||||
public ActivitySignRecord() {
|
||||
}
|
||||
|
||||
// Property accessors
|
||||
@Id
|
||||
@GeneratedValue(strategy = IDENTITY)
|
||||
@Column(name = "id", unique = true, nullable = false)
|
||||
public int getId() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Column(name = "user_id", nullable = false, unique = true)
|
||||
public int getUserId() {
|
||||
return this.userId;
|
||||
}
|
||||
|
||||
public void setUserId(int userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
@Column(name = "days", nullable = false)
|
||||
public int getDays() {
|
||||
return this.days;
|
||||
}
|
||||
|
||||
public void setDays(int days) {
|
||||
this.days = days;
|
||||
}
|
||||
|
||||
@Column(name = "start_time", length = 19)
|
||||
public String getStartTime() {
|
||||
return this.startTime;
|
||||
}
|
||||
|
||||
public void setStartTime(String startTime) {
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
@Column(name = "last_sign_time", length = 19)
|
||||
public String getLastSignTime() {
|
||||
return this.lastSignTime;
|
||||
}
|
||||
|
||||
public void setLastSignTime(String lastSignTime) {
|
||||
this.lastSignTime = lastSignTime;
|
||||
}
|
||||
|
||||
@Column(name = "last_collect_time", length = 19)
|
||||
public String getLastCollectTime() {
|
||||
return lastCollectTime;
|
||||
}
|
||||
|
||||
public void setLastCollectTime(String lastCollectTime) {
|
||||
this.lastCollectTime = lastCollectTime;
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package activity.domains.content.entity.activity;
|
||||
|
||||
/**
|
||||
* 绑定资料活动
|
||||
*/
|
||||
public class RebateRulesBind {
|
||||
|
||||
private double money;
|
||||
|
||||
public RebateRulesBind() {
|
||||
|
||||
}
|
||||
|
||||
public double getMoney() {
|
||||
return money;
|
||||
}
|
||||
|
||||
public void setMoney(double money) {
|
||||
this.money = money;
|
||||
}
|
||||
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package activity.domains.content.entity.activity;
|
||||
|
||||
/**
|
||||
* 抢红包活动
|
||||
*/
|
||||
public class RebateRulesPacket {
|
||||
|
||||
private double cost;
|
||||
|
||||
public RebateRulesPacket() {
|
||||
|
||||
}
|
||||
|
||||
public double getCost() {
|
||||
return cost;
|
||||
}
|
||||
|
||||
public void setCost(double cost) {
|
||||
this.cost = cost;
|
||||
}
|
||||
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package activity.domains.content.entity.activity;
|
||||
|
||||
/**
|
||||
* 开始大酬宾,连环嗨不停
|
||||
*/
|
||||
public class RebateRulesRechargeLoop {
|
||||
|
||||
private double s1Recharge;
|
||||
private double s1Cost;
|
||||
private double s1Reward;
|
||||
|
||||
private double s2Cost;
|
||||
private double s2Reward;
|
||||
private int s2Times;
|
||||
|
||||
private double s3Reward;
|
||||
private int s3Limit;
|
||||
|
||||
public RebateRulesRechargeLoop() {
|
||||
|
||||
}
|
||||
|
||||
public double getS1Recharge() {
|
||||
return s1Recharge;
|
||||
}
|
||||
|
||||
public void setS1Recharge(double s1Recharge) {
|
||||
this.s1Recharge = s1Recharge;
|
||||
}
|
||||
|
||||
public double getS1Cost() {
|
||||
return s1Cost;
|
||||
}
|
||||
|
||||
public void setS1Cost(double s1Cost) {
|
||||
this.s1Cost = s1Cost;
|
||||
}
|
||||
|
||||
public double getS1Reward() {
|
||||
return s1Reward;
|
||||
}
|
||||
|
||||
public void setS1Reward(double s1Reward) {
|
||||
this.s1Reward = s1Reward;
|
||||
}
|
||||
|
||||
public double getS2Cost() {
|
||||
return s2Cost;
|
||||
}
|
||||
|
||||
public void setS2Cost(double s2Cost) {
|
||||
this.s2Cost = s2Cost;
|
||||
}
|
||||
|
||||
public double getS2Reward() {
|
||||
return s2Reward;
|
||||
}
|
||||
|
||||
public void setS2Reward(double s2Reward) {
|
||||
this.s2Reward = s2Reward;
|
||||
}
|
||||
|
||||
public int getS2Times() {
|
||||
return s2Times;
|
||||
}
|
||||
|
||||
public void setS2Times(int s2Times) {
|
||||
this.s2Times = s2Times;
|
||||
}
|
||||
|
||||
public double getS3Reward() {
|
||||
return s3Reward;
|
||||
}
|
||||
|
||||
public void setS3Reward(double s3Reward) {
|
||||
this.s3Reward = s3Reward;
|
||||
}
|
||||
|
||||
public int getS3Limit() {
|
||||
return s3Limit;
|
||||
}
|
||||
|
||||
public void setS3Limit(int s3Limit) {
|
||||
this.s3Limit = s3Limit;
|
||||
}
|
||||
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package activity.domains.content.entity.activity;
|
||||
|
||||
/**
|
||||
* 佣金活动
|
||||
*/
|
||||
public class RebateRulesReward {
|
||||
|
||||
private double money;
|
||||
private double rewardUp1;
|
||||
private double rewardUp2;
|
||||
|
||||
public RebateRulesReward() {
|
||||
|
||||
}
|
||||
|
||||
public double getMoney() {
|
||||
return money;
|
||||
}
|
||||
|
||||
public void setMoney(double money) {
|
||||
this.money = money;
|
||||
}
|
||||
|
||||
public double getRewardUp1() {
|
||||
return rewardUp1;
|
||||
}
|
||||
|
||||
public void setRewardUp1(double rewardUp1) {
|
||||
this.rewardUp1 = rewardUp1;
|
||||
}
|
||||
|
||||
public double getRewardUp2() {
|
||||
return rewardUp2;
|
||||
}
|
||||
|
||||
public void setRewardUp2(double rewardUp2) {
|
||||
this.rewardUp2 = rewardUp2;
|
||||
}
|
||||
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package activity.domains.content.entity.activity;
|
||||
|
||||
/**
|
||||
* 薪资活动
|
||||
*/
|
||||
public class RebateRulesSalary {
|
||||
|
||||
private double money;
|
||||
private double reward;
|
||||
private int people;
|
||||
|
||||
public RebateRulesSalary() {
|
||||
|
||||
}
|
||||
|
||||
public int getPeople() {
|
||||
return people;
|
||||
}
|
||||
|
||||
public void setPeople(int people) {
|
||||
this.people = people;
|
||||
}
|
||||
|
||||
public double getMoney() {
|
||||
return money;
|
||||
}
|
||||
|
||||
public void setMoney(double money) {
|
||||
this.money = money;
|
||||
}
|
||||
|
||||
public double getReward() {
|
||||
return reward;
|
||||
}
|
||||
|
||||
public void setReward(double reward) {
|
||||
this.reward = reward;
|
||||
}
|
||||
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package activity.domains.content.entity.activity;
|
||||
|
||||
/**
|
||||
* 签到活动
|
||||
*/
|
||||
public class RebateRulesSign {
|
||||
|
||||
private double day;
|
||||
private double cost;
|
||||
private double reward;
|
||||
|
||||
public RebateRulesSign() {
|
||||
|
||||
}
|
||||
|
||||
public double getDay() {
|
||||
return day;
|
||||
}
|
||||
|
||||
public void setDay(double day) {
|
||||
this.day = day;
|
||||
}
|
||||
|
||||
public double getCost() {
|
||||
return cost;
|
||||
}
|
||||
|
||||
public void setCost(double cost) {
|
||||
this.cost = cost;
|
||||
}
|
||||
|
||||
public double getReward() {
|
||||
return reward;
|
||||
}
|
||||
|
||||
public void setReward(double reward) {
|
||||
this.reward = reward;
|
||||
}
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package activity.domains.content.vo.activity;
|
||||
|
||||
public class ActivityCostDrawInfoVo {
|
||||
private double todayCost;//今日已消费金额
|
||||
private double mayDraw;//可领取金额/或已领金额
|
||||
private int isReceived; // 是否已领取 0:不可领取 、1:可领取、2已领取
|
||||
public double getTodayCost() {
|
||||
return todayCost;
|
||||
}
|
||||
public void setTodayCost(double todayCost) {
|
||||
this.todayCost = todayCost;
|
||||
}
|
||||
public double getMayDraw() {
|
||||
return mayDraw;
|
||||
}
|
||||
public void setMayDraw(double mayDraw) {
|
||||
this.mayDraw = mayDraw;
|
||||
}
|
||||
public int getIsReceived() {
|
||||
return isReceived;
|
||||
}
|
||||
public void setIsReceived(int isReceived) {
|
||||
this.isReceived = isReceived;
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package activity.domains.content.vo.activity;
|
||||
|
||||
public class ActivityCostInfoVo {
|
||||
private double cost;//需要消费的金额
|
||||
private double prizeMoney;//对应的奖励
|
||||
|
||||
public double getCost() {
|
||||
return cost;
|
||||
}
|
||||
public void setCost(double cost) {
|
||||
this.cost = cost;
|
||||
}
|
||||
public double getPrizeMoney() {
|
||||
return prizeMoney;
|
||||
}
|
||||
public void setPrizeMoney(double prizeMoney) {
|
||||
this.prizeMoney = prizeMoney;
|
||||
}
|
||||
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
// package activity.domains.content.vo.activity;
|
||||
//
|
||||
// import lottery.domains.content.dao.UserInfoDao;
|
||||
// import lottery.domains.content.entity.UserInfo;
|
||||
// import lottery.domains.pool.DataFactory;
|
||||
// import activity.domains.content.entity.ActivityPacketInfo;
|
||||
//
|
||||
// public class ActivityPacketInfoVO {
|
||||
//
|
||||
// private String username;
|
||||
// private ActivityPacketInfo bean;
|
||||
// private String avatar = "000";//默认为系统小图标
|
||||
//
|
||||
// public ActivityPacketInfoVO(ActivityPacketInfo bean, DataFactory dataFactory, UserInfoDao dao){
|
||||
// this.bean = bean;
|
||||
// if(bean.getUserId() != -1){
|
||||
// this.username = dataFactory.getUser(bean.getUserId()).getUsername();
|
||||
// UserInfo userInfo = dao.get(bean.getUserId());
|
||||
// if(userInfo != null){
|
||||
// this.avatar = userInfo.getAvatar()+"";
|
||||
// }
|
||||
// }else{
|
||||
// //系统红包
|
||||
// this.username = "红杉系统福利";
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public String getAvatar() {
|
||||
// return avatar;
|
||||
// }
|
||||
//
|
||||
// public void setAvatar(String avatar) {
|
||||
// this.avatar = avatar;
|
||||
// }
|
||||
// public String getUsername() {
|
||||
// return username;
|
||||
// }
|
||||
// public void setUsername(String username) {
|
||||
// this.username = username;
|
||||
// }
|
||||
// public ActivityPacketInfo getBean() {
|
||||
// return bean;
|
||||
// }
|
||||
// public void setBean(ActivityPacketInfo bean) {
|
||||
// this.bean = bean;
|
||||
// }
|
||||
//
|
||||
// }
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package activity.domains.content.vo.activity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class ActivityRebateVo {
|
||||
private List<ActivityCostInfoVo> costInfo;
|
||||
private int status;//状态(0为正在进行,-1 为已停止)
|
||||
|
||||
public List<ActivityCostInfoVo> getCostInfo() {
|
||||
return costInfo;
|
||||
}
|
||||
public void setCostInfo(List<ActivityCostInfoVo> costInfo) {
|
||||
this.costInfo = costInfo;
|
||||
}
|
||||
public int getStatus() {
|
||||
return status;
|
||||
}
|
||||
public void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package activity.domains.content.vo.activity;
|
||||
|
||||
import activity.domains.content.entity.activity.RebateRulesRechargeLoop;
|
||||
|
||||
public class ActivityRechargeLoopVO {
|
||||
|
||||
private double s1Recharge; // 当前充值
|
||||
private double s1Cost; // 当前消费
|
||||
private double s1Reward; // 奖励金额
|
||||
private boolean s1Available = false; // 是否达到要求
|
||||
private boolean s1Received = false; // 是否领取
|
||||
|
||||
private double s2Cost; // 当前消费
|
||||
private int s2Times; // 已进行次数
|
||||
private boolean s2Available = false; // 是否达到要求
|
||||
private boolean s2Received = false; // 是否领取
|
||||
|
||||
private boolean s3Available = false; // 是否达到要求
|
||||
private boolean s3Received = false; // 是否领取
|
||||
|
||||
private RebateRulesRechargeLoop rules;
|
||||
|
||||
public ActivityRechargeLoopVO() {
|
||||
|
||||
}
|
||||
|
||||
public double getS1Recharge() {
|
||||
return s1Recharge;
|
||||
}
|
||||
|
||||
public void setS1Recharge(double s1Recharge) {
|
||||
this.s1Recharge = s1Recharge;
|
||||
}
|
||||
|
||||
public double getS1Cost() {
|
||||
return s1Cost;
|
||||
}
|
||||
|
||||
public void setS1Cost(double s1Cost) {
|
||||
this.s1Cost = s1Cost;
|
||||
}
|
||||
|
||||
public double getS1Reward() {
|
||||
return s1Reward;
|
||||
}
|
||||
|
||||
public void setS1Reward(double s1Reward) {
|
||||
this.s1Reward = s1Reward;
|
||||
}
|
||||
|
||||
public boolean isS1Available() {
|
||||
return s1Available;
|
||||
}
|
||||
|
||||
public void setS1Available(boolean s1Available) {
|
||||
this.s1Available = s1Available;
|
||||
}
|
||||
|
||||
public boolean isS1Received() {
|
||||
return s1Received;
|
||||
}
|
||||
|
||||
public void setS1Received(boolean s1Received) {
|
||||
this.s1Received = s1Received;
|
||||
}
|
||||
|
||||
public double getS2Cost() {
|
||||
return s2Cost;
|
||||
}
|
||||
|
||||
public void setS2Cost(double s2Cost) {
|
||||
this.s2Cost = s2Cost;
|
||||
}
|
||||
|
||||
public int getS2Times() {
|
||||
return s2Times;
|
||||
}
|
||||
|
||||
public void setS2Times(int s2Times) {
|
||||
this.s2Times = s2Times;
|
||||
}
|
||||
|
||||
public boolean isS2Available() {
|
||||
return s2Available;
|
||||
}
|
||||
|
||||
public void setS2Available(boolean s2Available) {
|
||||
this.s2Available = s2Available;
|
||||
}
|
||||
|
||||
public boolean isS2Received() {
|
||||
return s2Received;
|
||||
}
|
||||
|
||||
public void setS2Received(boolean s2Received) {
|
||||
this.s2Received = s2Received;
|
||||
}
|
||||
|
||||
public boolean isS3Available() {
|
||||
return s3Available;
|
||||
}
|
||||
|
||||
public void setS3Available(boolean s3Available) {
|
||||
this.s3Available = s3Available;
|
||||
}
|
||||
|
||||
public boolean isS3Received() {
|
||||
return s3Received;
|
||||
}
|
||||
|
||||
public void setS3Received(boolean s3Received) {
|
||||
this.s3Received = s3Received;
|
||||
}
|
||||
|
||||
public RebateRulesRechargeLoop getRules() {
|
||||
return rules;
|
||||
}
|
||||
|
||||
public void setRules(RebateRulesRechargeLoop rules) {
|
||||
this.rules = rules;
|
||||
}
|
||||
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package activity.domains.content.vo.activity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import activity.domains.content.entity.activity.RebateRulesSalary;
|
||||
|
||||
public class ActivitySalaryVO {
|
||||
|
||||
private double totalMoney;
|
||||
private double totalProfit;
|
||||
private List<RebateRulesSalary> rlist;
|
||||
private boolean isReceived;
|
||||
private int people;
|
||||
|
||||
public int getPeople() {
|
||||
return people;
|
||||
}
|
||||
|
||||
public void setPeople(int people) {
|
||||
this.people = people;
|
||||
}
|
||||
|
||||
public ActivitySalaryVO() {
|
||||
|
||||
}
|
||||
|
||||
public double getTotalMoney() {
|
||||
return totalMoney;
|
||||
}
|
||||
|
||||
public void setTotalMoney(double totalMoney) {
|
||||
this.totalMoney = totalMoney;
|
||||
}
|
||||
|
||||
public double getTotalProfit() {
|
||||
return totalProfit;
|
||||
}
|
||||
|
||||
public void setTotalProfit(double totalProfit) {
|
||||
this.totalProfit = totalProfit;
|
||||
}
|
||||
|
||||
public List<RebateRulesSalary> getRlist() {
|
||||
return rlist;
|
||||
}
|
||||
|
||||
public void setRlist(List<RebateRulesSalary> rlist) {
|
||||
this.rlist = rlist;
|
||||
}
|
||||
|
||||
public boolean isReceived() {
|
||||
return isReceived;
|
||||
}
|
||||
|
||||
public void setReceived(boolean isReceived) {
|
||||
this.isReceived = isReceived;
|
||||
}
|
||||
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package activity.domains.content.vo.activity;
|
||||
|
||||
public class ActivitySignVO {
|
||||
|
||||
private int days; // 已经连续签到天数
|
||||
private boolean todaySigned; // 今天是否已经签到过了
|
||||
|
||||
public ActivitySignVO() {}
|
||||
|
||||
public ActivitySignVO(int days, boolean todaySigned) {
|
||||
this.days = days;
|
||||
this.todaySigned = todaySigned;
|
||||
}
|
||||
|
||||
public int getDays() {
|
||||
return days;
|
||||
}
|
||||
|
||||
public void setDays(int days) {
|
||||
this.days = days;
|
||||
}
|
||||
|
||||
public boolean isTodaySigned() {
|
||||
return todaySigned;
|
||||
}
|
||||
|
||||
public void setTodaySigned(boolean todaySigned) {
|
||||
this.todaySigned = todaySigned;
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package activity.domains.content.vo.activity;
|
||||
|
||||
public class ActivityWheelVO {
|
||||
private double todayCost; //今日已消费金额
|
||||
private boolean todayDrew; // 今天是否已经参与过活动了
|
||||
private double remainCost; // 今日剩余消费可参与活动
|
||||
private double todayPrize; // 今日中奖
|
||||
private String date;
|
||||
private boolean enabled; // 活动是否开启中
|
||||
|
||||
public double getTodayCost() {
|
||||
return todayCost;
|
||||
}
|
||||
|
||||
public void setTodayCost(double todayCost) {
|
||||
this.todayCost = todayCost;
|
||||
}
|
||||
|
||||
public boolean isTodayDrew() {
|
||||
return todayDrew;
|
||||
}
|
||||
|
||||
public void setTodayDrew(boolean todayDrew) {
|
||||
this.todayDrew = todayDrew;
|
||||
}
|
||||
|
||||
public double getRemainCost() {
|
||||
return remainCost;
|
||||
}
|
||||
|
||||
public void setRemainCost(double remainCost) {
|
||||
this.remainCost = remainCost;
|
||||
}
|
||||
|
||||
public double getTodayPrize() {
|
||||
return todayPrize;
|
||||
}
|
||||
|
||||
public void setTodayPrize(double todayPrize) {
|
||||
this.todayPrize = todayPrize;
|
||||
}
|
||||
|
||||
public String getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(String date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
package activity.web.content;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import activity.domains.content.biz.ActivityRechargeLoopService;
|
||||
import activity.domains.content.biz.ActivitySignService;
|
||||
import activity.domains.content.entity.ActivityRebate;
|
||||
import lottery.domains.content.biz.ActivityRebateService;
|
||||
import lottery.domains.content.biz.ActivityRebateWheelService;
|
||||
import lottery.domains.content.biz.ActivityRedPacketRainBillService;
|
||||
import lottery.domains.content.biz.UserLotteryReportService;
|
||||
import lottery.domains.content.biz.read.UserLotteryReportReadService;
|
||||
import lottery.domains.content.global.Global;
|
||||
import lottery.domains.pool.DataFactory;
|
||||
import lottery.web.WUC;
|
||||
import lottery.web.WebJSON;
|
||||
import lottery.web.helper.AbstractActionController;
|
||||
import lottery.web.helper.session.SessionUser;
|
||||
|
||||
/**
|
||||
* 活动控制服务类
|
||||
* <p>Title: ActivityController</p>
|
||||
* <p>Description: </p>
|
||||
* @author James
|
||||
* @date 2018年2月3日
|
||||
*/
|
||||
@Controller
|
||||
public class ActivityController extends AbstractActionController {
|
||||
|
||||
|
||||
/* @Autowired
|
||||
private ActivitySalaryService aSalaryService;
|
||||
*/
|
||||
@Autowired
|
||||
private ActivityRechargeLoopService aRechargeLoopService;
|
||||
|
||||
@Autowired
|
||||
private ActivitySignService aSignService;
|
||||
|
||||
@Autowired
|
||||
private ActivityRebateWheelService wheelService;
|
||||
|
||||
@Autowired
|
||||
private UserLotteryReportService lotteryReportService;
|
||||
|
||||
//
|
||||
// @Autowired
|
||||
// private ActivityPacketService packetService;
|
||||
|
||||
// @Autowired
|
||||
// private UserSecurityService uSecurityService;
|
||||
|
||||
// @Autowired
|
||||
// private ActivityCostService activityCostService;
|
||||
|
||||
//返点活动服务类
|
||||
@Autowired
|
||||
private ActivityRebateService activityRebateService;
|
||||
|
||||
|
||||
|
||||
@Autowired
|
||||
private ActivityRedPacketRainBillService rainBillService;
|
||||
|
||||
@Autowired
|
||||
private UserLotteryReportReadService uLotteryReportReadService;
|
||||
|
||||
|
||||
/**
|
||||
* DataFactory
|
||||
*/
|
||||
@Autowired
|
||||
private DataFactory dataFactory;
|
||||
//
|
||||
// @RequestMapping(value = WUC.ACTIVITY_SALARY_ZS_LOAD, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public Map<String, Object> ACTIVITY_SALARY_ZS_LOAD(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
// if (sessionUser == null) {
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// User uEntity = uService.getById(sessionUser.getId());
|
||||
// if (uEntity == null) {
|
||||
// super.logOut(session, request);
|
||||
// json.set(2, "2-10"); // 您的账户信息发生变更,请重新登录
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// if(uEntity.getType() == Global.USER_TYPE_PROXY) {
|
||||
// // System.out.println(uCodePointUtil.isZhiShu(uEntity));
|
||||
// if(uCodePointUtil.isZhiShu(uEntity)) {
|
||||
// int type = 1;
|
||||
// ActivitySalaryVO bean = aSalaryService.get(uEntity.getId(), type);
|
||||
// if(bean != null) {
|
||||
// json.data("data", bean);
|
||||
// json.set(0, "0-1");
|
||||
// } else {
|
||||
// json.set(2, "2-4001");
|
||||
// }
|
||||
// } else {
|
||||
// json.set(2, "2-4003");
|
||||
// }
|
||||
// }
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// @RequestMapping(value = WUC.ACTIVITY_SALARY_ZS_RECEIVE, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public synchronized Map<String, Object> ACTIVITY_SALARY_ZS_RECEIVE(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
// if (sessionUser == null) {
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// User uEntity = uService.getById(sessionUser.getId());
|
||||
// if (uEntity == null) {
|
||||
// super.logOut(session, request);
|
||||
// json.set(2, "2-10"); // 您的账户信息发生变更,请重新登录
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// if(uEntity.getType() == Global.USER_TYPE_PROXY) {
|
||||
// System.out.println(uCodePointUtil.isZhiShu(uEntity));
|
||||
// if(uCodePointUtil.isZhiShu(uEntity)) {
|
||||
// int type = 1;
|
||||
// boolean flag = aSalaryService.receive(json, uEntity.getId(), type);
|
||||
// if(flag) {
|
||||
// json.set(0, "0-1");
|
||||
// } else {
|
||||
// if(!StringUtil.isNotNull(json.getMessage())) {
|
||||
// json.set(1, "1-1");
|
||||
// }
|
||||
// }
|
||||
// } else {
|
||||
// json.set(2, "2-4003");
|
||||
// }
|
||||
// }
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// @RequestMapping(value = WUC.ACTIVITY_SALARY_ZD_LOAD, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public Map<String, Object> ACTIVITY_SALARY_ZD_LOAD(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
// if (sessionUser == null) {
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// User uEntity = uService.getById(sessionUser.getId());
|
||||
// if (uEntity == null) {
|
||||
// super.logOut(session, request);
|
||||
// json.set(2, "2-10"); // 您的账户信息发生变更,请重新登录
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// if(uEntity.getType() == Global.USER_TYPE_PROXY) {
|
||||
// if(uCodePointUtil.isSpecialZhiShu(uEntity)) {
|
||||
// int type = 2;
|
||||
// ActivitySalaryVO bean = aSalaryService.get(uEntity.getId(), type);
|
||||
// if(bean != null) {
|
||||
// json.data("data", bean);
|
||||
// json.set(0, "0-1");
|
||||
// } else {
|
||||
// json.set(2, "2-4001");
|
||||
// }
|
||||
// } else {
|
||||
// json.set(2, "2-4004");
|
||||
// }
|
||||
// }
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// @RequestMapping(value = WUC.ACTIVITY_SALARY_ZD_RECEIVE, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public synchronized Map<String, Object> ACTIVITY_SALARY_ZD_RECEIVE(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
// if (sessionUser == null) {
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// User uEntity = uService.getById(sessionUser.getId());
|
||||
// if (uEntity == null) {
|
||||
// super.logOut(session, request);
|
||||
// json.set(2, "2-10"); // 您的账户信息发生变更,请重新登录
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// if(uEntity.getType() == Global.USER_TYPE_PROXY) {
|
||||
// if(uCodePointUtil.isSpecialZhiShu(uEntity)) {
|
||||
// int type = 2;
|
||||
// boolean flag = aSalaryService.receive(json, uEntity.getId(), type);
|
||||
// if(flag) {
|
||||
// json.set(0, "0-1");
|
||||
// } else {
|
||||
// if(!StringUtil.isNotNull(json.getMessage())) {
|
||||
// json.set(1, "1-1");
|
||||
// }
|
||||
// }
|
||||
// } else {
|
||||
// json.set(2, "2-4004");
|
||||
// }
|
||||
// }
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// @RequestMapping(value = WUC.ACTIVITY_RECHARGE_LOOP_LOAD, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public Map<String, Object> ACTIVITY_RECHARGE_LOOP_LOAD(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
// if (sessionUser == null) {
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// ActivityRechargeLoopVO bean = aRechargeLoopService.get(sessionUser.getId());
|
||||
// if(bean != null) {
|
||||
// json.data("data", bean);
|
||||
// json.set(0, "0-1");
|
||||
// } else {
|
||||
// json.set(2, "2-4001");
|
||||
// }
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// @RequestMapping(value = WUC.ACTIVITY_RECHARGE_LOOP_RECEIVE, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public Map<String, Object> ACTIVITY_RECHARGE_LOOP_RECEIVE(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
// if (sessionUser == null) {
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// String ip = HttpUtil.getRealIp(request);
|
||||
// int step = HttpUtil.getIntParameter(request, "step");
|
||||
// boolean flag = aRechargeLoopService.receive(json, sessionUser.getId(), ip, step);
|
||||
// if(flag) {
|
||||
// json.set(0, "0-1");
|
||||
// } else {
|
||||
// if(!StringUtil.isNotNull(json.getMessage())) {
|
||||
// json.set(1, "1-1");
|
||||
// }
|
||||
// }
|
||||
// return json.toJson();
|
||||
// }
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 加载全部进行中的活动
|
||||
* @param session
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = WUC.ACTIVITY_LIST_LOAD, method = { RequestMethod.GET,RequestMethod.POST })
|
||||
@ResponseBody
|
||||
public Map<String, Object> ACTIVITY_LIST_LOAD(HttpSession session, HttpServletRequest request) {
|
||||
WebJSON json = new WebJSON(dataFactory);
|
||||
SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
if (sessionUser == null) {
|
||||
return json.toJson();
|
||||
}
|
||||
if (sessionUser.getUpid() != 0) {
|
||||
List<ActivityRebate> rebateList = new ArrayList<ActivityRebate>();
|
||||
json.data("rebateList", rebateList);
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
if (sessionUser.getId() == Global.USER_TOP_ID) {
|
||||
json.set(2, "2-13");
|
||||
return json.toJson();
|
||||
}
|
||||
//查询所有返点活动集合
|
||||
List<ActivityRebate> rebateList = activityRebateService.getRebateActivityList();
|
||||
|
||||
json.data("rebateList", rebateList);
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
|
||||
/* @RequestMapping(value = WUC.ACTIVITY_WHEEL_DRAW, method = { RequestMethod.POST })
|
||||
@ResponseBody
|
||||
public Map<String, Object> ACTIVITY_WHEEL_DRAW(HttpSession session, HttpServletRequest request) {
|
||||
WebJSON json = new WebJSON(dataFactory);
|
||||
SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
if (sessionUser == null) {
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
if (sessionUser.getId() == Global.USER_TOP_ID) {
|
||||
json.set(2, "2-13");
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
String ip = HttpUtil.getRealIp(json, request);
|
||||
if (ip == null) {
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
Double amount = wheelService.draw(json, sessionUser.getId(), ip);
|
||||
// amount == null || amount <= 0 活动参与失败并返回失败原因
|
||||
// amount > 0 活动参与成功并返回金额
|
||||
if(amount != null && amount > 0) {
|
||||
String amountStr = MathUtil.doubleUpTOString(amount);
|
||||
json.data("amount", amountStr);
|
||||
json.set(0, "0-1");
|
||||
}
|
||||
return json.toJson();
|
||||
}*/
|
||||
|
||||
/* //
|
||||
// @RequestMapping(value = WUC.ACTIVITY_PACKET_LOAD, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public Map<String, Object> ACTIVITY_PACKET_LOAD(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// User uEntity = super.getCurrUser(session, request);
|
||||
// String ip = HttpUtil.getRealIp(request);
|
||||
// if(uEntity != null) {
|
||||
// List<ActivityPacketInfo> list = packetService.getAvaliablePackets(uEntity.getId(), ip);
|
||||
// List<ActivityPacketInfoVO> data = new ArrayList<ActivityPacketInfoVO>();
|
||||
// for (ActivityPacketInfo activityPacketInfo : list) {
|
||||
// ActivityPacketInfoVO vo = new ActivityPacketInfoVO(activityPacketInfo, dataFactory, userInfoDao);
|
||||
// data.add(vo);
|
||||
// }
|
||||
// json.data("data", data);
|
||||
// }
|
||||
// json.set(0, "0-1");
|
||||
// return json.toJson();
|
||||
// }
|
||||
*/
|
||||
// @RequestMapping(value = WUC.ACTIVITY_PACKET_SEND, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public synchronized Map<String, Object> ACTIVITY_PACKET_SEND(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// User uEntity = super.getCurrUser(session, request);
|
||||
// if(uEntity != null) {
|
||||
// String loadType = request.getParameter("loadType");//loadSecurity加载密保问题 send发送红包
|
||||
// if(loadType.equals("loadSecurity")){
|
||||
// loadSecurityInfo(json, uEntity);
|
||||
// }else{
|
||||
// int count = Integer.parseInt(request.getParameter("count"));
|
||||
// double amount = Double.parseDouble(request.getParameter("amount"));
|
||||
// amount = Math.abs(amount);
|
||||
// String withdrawPwd = request.getParameter("withdrawPwd");
|
||||
// int questionId = Integer.parseInt(request.getParameter("questionId"));
|
||||
// String answer = request.getParameter("answer");
|
||||
// boolean validateSecurity = uSecurityService.validateSecurity(questionId, uEntity.getId(), answer);
|
||||
// boolean validateWithdrawPwd = CipherUtil.validatePassword(uEntity.getWithdrawPassword(), withdrawPwd);
|
||||
// if(!validateSecurity){
|
||||
// json.set(2, "2-1010");
|
||||
// }else if(!validateWithdrawPwd){
|
||||
// json.set(2, "2-1009");
|
||||
// }else if(uEntity.getLotteryMoney() < amount){
|
||||
// json.set(2, "2-1109");
|
||||
// }else{
|
||||
// packetService.doSendPacket(count, amount, uEntity.getId());
|
||||
// json.set(0, "0-1");
|
||||
// }
|
||||
// }
|
||||
// } else {
|
||||
// String message = (String) request.getAttribute("message");
|
||||
// message = StringUtil.isNotNull(message) ? message : "2-1006";
|
||||
// json.set(2, message);
|
||||
// }
|
||||
// return json.toJson();
|
||||
// }
|
||||
|
||||
// private void loadSecurityInfo(WebJSON json, User uEntity) {
|
||||
// UserSecurityVO securityVO = uSecurityService.getRandomByUserId(uEntity.getId());
|
||||
// if(securityVO == null){
|
||||
// json.set(2, "2-1033");
|
||||
// }else if(!StringUtil.isNotNull(uEntity.getWithdrawPassword()) ){
|
||||
// json.set(2, "2-1072");
|
||||
// }else{
|
||||
// json.set(0, "0-1");
|
||||
// json.data("data", securityVO);
|
||||
// }
|
||||
// }
|
||||
|
||||
// @RequestMapping(value = WUC.ACTIVITY_PACKET_RECEIVE, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public synchronized Map<String, Object> ACTIVITY_PACKET_RECEIVE(HttpSession session, HttpServletRequest request) {
|
||||
// User uEntity = super.getCurrUser(session, request);
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// String ip = HttpUtil.getRealIp(request);
|
||||
// if(uEntity != null) {
|
||||
// int id = Integer.parseInt(request.getParameter("id"));
|
||||
// List<ActivityPacketInfo> list = packetService.getAvaliablePackets(uEntity.getId(), ip);
|
||||
// if(list != null && !list.isEmpty()){
|
||||
// ActivityPacketInfo packetInfo = packetService.validateIp(id, ip, list);
|
||||
// if(packetInfo == null){
|
||||
// json.set(2, "2-4010");
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// double minCost = packetService.validateCost(uEntity.getId());
|
||||
// if(minCost > -1){
|
||||
// json.set(2, "2-4009", minCost);
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// ActivityPacketBill packetBill = packetService.doGrabPacket(packetInfo, uEntity.getId(), ip);
|
||||
// if(packetBill == null){
|
||||
// json.set(2, "2-4008");
|
||||
// }else{
|
||||
// json.data("data", packetBill);
|
||||
// json.set(0, "0-1");
|
||||
// }
|
||||
// }else{
|
||||
// //手慢了红包被抢
|
||||
// json.set(2, "2-4008");
|
||||
// }
|
||||
// } else {
|
||||
// String message = (String) request.getAttribute("message");
|
||||
// message = StringUtil.isNotNull(message) ? message : "2-1006";
|
||||
// json.set(2, message);
|
||||
// }
|
||||
// return json.toJson();
|
||||
// }
|
||||
|
||||
|
||||
// /**
|
||||
// * 加载消费奖励活动详情
|
||||
// * @param session
|
||||
// * @param request
|
||||
// * @return
|
||||
// */
|
||||
// @RequestMapping(value = WUC.ACTIVITY_COST_LOAD, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public Map<String, Object> ACTIVITY_COST_LOAD(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
// if (sessionUser == null) {
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// ActivityRebateVo bean = activityCostService.getCostInfo(Global.ACTIVITY_REBATE_COST);
|
||||
// if(bean != null) {
|
||||
// json.data("data", bean);
|
||||
// json.set(0, "0-1");
|
||||
// } else {
|
||||
// json.set(2, "2-4001");
|
||||
// }
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 领取情况
|
||||
// * @param session
|
||||
// * @param request
|
||||
// * @return
|
||||
// */
|
||||
// @RequestMapping(value = WUC.ACTIVITY_COST_CONSUMPTION, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public Map<String, Object> ACTIVITY_COST_CONSUMPTION(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
// if (sessionUser == null) {
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
|
||||
// Date now = new Date();
|
||||
// String sTime = fmt.format(now) +" 00:00:00";
|
||||
// String eTime = fmt.format(now) +" 23:59:59";
|
||||
// ActivityCostDrawInfoVo bean = activityCostService.getCostDarwInfo(sessionUser.getId(),sTime,eTime);
|
||||
// if(bean != null) {
|
||||
// json.data("data", bean);
|
||||
// json.set(0, "0-1");
|
||||
// } else {
|
||||
// json.set(2, "2-4001");
|
||||
// }
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
//
|
||||
// /**
|
||||
// * 领取奖励
|
||||
// * @param session
|
||||
// * @param request
|
||||
// * @return
|
||||
// */
|
||||
// @RequestMapping(value = WUC.ACTIVITY_COST_RECEIVE, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public Map<String, Object> ACTIVITY_COST_RECEIVE(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
// if (sessionUser == null) {
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// ActivityRebate activityInfo = activityRebateDao.getByStatusAndType(Global.ACTIVITY_REBATE_COST,
|
||||
// Global.ACTIVITY_STATUS_OPEN);
|
||||
// //活动不存在
|
||||
// if(activityInfo == null){
|
||||
// json.set(2, "2-4001");
|
||||
// return json.toJson();
|
||||
// }
|
||||
// String ip = HttpUtil.getRealIp(request).trim();
|
||||
// ActivityCostBill lastCost = activityCostService.getLastCostBillInfoByIp(ip);
|
||||
//
|
||||
// // ActivityCostBill lastCost = activityCostService.getLastCostBillInfo(uEntity.getId());
|
||||
// //和上次领取的IP不同
|
||||
// if(lastCost !=null &&
|
||||
// !String.valueOf(lastCost.getUserId()).equals(String.valueOf(sessionUser.getId()))){
|
||||
// json.set(2, "2-4011");
|
||||
// return json.toJson();
|
||||
// }
|
||||
// SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
|
||||
// Date now = new Date();
|
||||
// String sTime = fmt.format(now) +" 00:00:00";
|
||||
// String eTime = fmt.format(now) +" 23:59:59";
|
||||
// //判断今天是否领取
|
||||
// ActivityCostBill bill = activityCostService.getToDayDrawInfo(sessionUser.getId(), sTime, eTime);
|
||||
// if (bill != null) {
|
||||
// json.set(2, "2-4012");
|
||||
// return json.toJson();
|
||||
// }
|
||||
// double costMoney = userBetsReadDao.getBillingOrder(sessionUser.getId(), sTime, eTime);
|
||||
// if(costMoney <=0){
|
||||
// json.set(2, "2-4013");
|
||||
// return json.toJson();
|
||||
// }
|
||||
// //根据活动配置得到对应的消费奖励
|
||||
// double prizeMoney = PrizeUtils.costConfigPrize(activityInfo.getRules(),costMoney);
|
||||
// if(prizeMoney > 0){
|
||||
// //最大限制8888
|
||||
// if(prizeMoney > 8888)
|
||||
// prizeMoney = 8888;
|
||||
// //领取奖励
|
||||
// boolean result = activityCostService.darwCostAward(sessionUser.getId(),
|
||||
// costMoney,prizeMoney, now, ip);
|
||||
// if(result){
|
||||
// ActivityCostDrawInfoVo drawInfo = new ActivityCostDrawInfoVo();
|
||||
// drawInfo.setIsReceived(Global.ACTIVITY_COST_STATUS_Y);//已领取
|
||||
// drawInfo.setMayDraw(prizeMoney);//已领金额
|
||||
// drawInfo.setTodayCost(costMoney);//领取时消费的金额
|
||||
// json.data("data", drawInfo);
|
||||
// json.set(0, "0-1");
|
||||
// }else{
|
||||
// json.set(2, "2-4014");
|
||||
// }
|
||||
// }else{
|
||||
// json.set(2, "2-4013");
|
||||
// }
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 领取红包雨金额
|
||||
// */
|
||||
// @RequestMapping(value = WUC.ACTIVITY_REDPACKET_COLLECT, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public Map<String, Object> ACTIVITY_REDPACKET_COLLECT(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
// if (sessionUser == null) {
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// String ip = HttpUtil.getRealIp(json, request);
|
||||
// if (ip == null) {
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// Double amount = rainBillService.collect(json, sessionUser.getId(), ip);
|
||||
// if(amount != null) {
|
||||
// json.data("amount", amount);
|
||||
// json.set(0, "0-1");
|
||||
// }
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// /**
|
||||
// * 获取红包雨时间
|
||||
// */
|
||||
// @RequestMapping(value = WUC.ACTIVITY_REDPACKET_TIME, method = { RequestMethod.POST })
|
||||
// @ResponseBody
|
||||
// public Map<String, Object> ACTIVITY_REDPACKET_TIME(HttpSession session, HttpServletRequest request) {
|
||||
// WebJSON json = new WebJSON(dataFactory);
|
||||
// SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
// if (sessionUser == null) {
|
||||
// return json.toJson();
|
||||
// }
|
||||
//
|
||||
// // 当前状态
|
||||
// ActivityRedPacketRainTime currentTime = dataFactory.getCurrentActivityRedPacketRainTime();
|
||||
//
|
||||
// boolean started = currentTime != null;
|
||||
// boolean allowAttend = false; // 是否允许参与红包雨
|
||||
// int nextSeconds = -1; // 下一轮的剩余秒数
|
||||
// if (started) {
|
||||
// String date = currentTime.getDate();
|
||||
// String hour = currentTime.getHour();
|
||||
// // 看用户本轮是否已经参与
|
||||
// ActivityRedPacketRainBill bill = rainBillService.getByUserIdAndDateAndHour(sessionUser.getId(), date, hour);
|
||||
// started = bill == null;
|
||||
// }
|
||||
//
|
||||
// // 查看用户今天的消费情况,来看是否允许参与今天的红包雨
|
||||
// if (started) {
|
||||
// String sDate = new Moment().toSimpleDate();
|
||||
// String eDate = new Moment().add(1, "days").toSimpleDate();
|
||||
// List<?> userCosts = uLotteryReportReadService.listAmountGroupByUserIds(new Integer[]{sessionUser.getId()}, sDate, eDate);
|
||||
// if (CollectionUtils.isNotEmpty(userCosts)) {
|
||||
// double minCost = dataFactory.getActivityRedPacketRainConfig().getMinCost();
|
||||
// Object[] userCostArr = (Object[]) userCosts.get(0);
|
||||
// double todayCost = (Double) userCostArr[1];
|
||||
// allowAttend = todayCost >= minCost;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// ActivityRedPacketRainTime nextTime = dataFactory.getNextActivityRedPacketRainTime(currentTime);
|
||||
// if (nextTime != null) {
|
||||
// Moment now = new Moment();
|
||||
// Moment nextStartTime = new Moment().fromTime(nextTime.getStartTime());
|
||||
// nextSeconds = nextStartTime.difference(now, "second");
|
||||
// }
|
||||
//
|
||||
// int currentEnd = 0;
|
||||
// if (currentTime != null) {
|
||||
// Moment now = new Moment();
|
||||
// Moment endTime = new Moment().fromTime(currentTime.getEndTime());
|
||||
// currentEnd = endTime.difference(now, "second");
|
||||
// if (currentEnd > 2) {
|
||||
// currentEnd -= 2;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// Map<String, Object> data = new HashMap<>();
|
||||
// data.put("currentStarted", started); // 本轮红包雨是否已经开启
|
||||
// data.put("allowAttend", allowAttend); // 是否允许参与红包雨
|
||||
// data.put("nextSeconds", nextSeconds); // 下一轮的剩余秒数
|
||||
// data.put("currentStartTime", currentTime == null ? "" : currentTime.getStartTime()); // 本轮开始时间
|
||||
// data.put("currentEndTime", currentTime == null ? "" : currentTime.getEndTime()); // 本轮结束时间
|
||||
// data.put("currentEnd", currentEnd); // 本轮XX秒后结束
|
||||
// json.data("data", data);
|
||||
// json.set(0, "0-1");
|
||||
// return json.toJson();
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package activity.web.content;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import activity.domains.content.biz.ActivitySignService;
|
||||
import activity.domains.content.entity.ActivityRebate;
|
||||
import activity.domains.content.vo.activity.ActivitySignVO;
|
||||
import lottery.domains.content.global.Global;
|
||||
import lottery.domains.pool.DataFactory;
|
||||
import lottery.web.WUC;
|
||||
import lottery.web.WebJSON;
|
||||
import lottery.web.helper.AbstractActionController;
|
||||
import lottery.web.helper.session.SessionUser;
|
||||
|
||||
/**
|
||||
* <p>Title: SignActivityController</p>
|
||||
* <p>Description: 签到活动服务类 </p>
|
||||
* @author James
|
||||
* @date 2018年2月3日
|
||||
*/
|
||||
@Controller
|
||||
public class SignActivityController extends AbstractActionController {
|
||||
|
||||
@Autowired
|
||||
private DataFactory dataFactory;
|
||||
@Autowired
|
||||
private ActivitySignService aSignService;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Title: ACTIVITY_SIGN_LOAD</p>
|
||||
* <p>Description: 加载签到活动</p>
|
||||
* @param session
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = WUC.ACTIVITY_SIGN_LOAD, method = { RequestMethod.POST })
|
||||
@ResponseBody
|
||||
public Map<String, Object> ACTIVITY_SIGN_LOAD(HttpSession session, HttpServletRequest request) {
|
||||
WebJSON json = new WebJSON(dataFactory);
|
||||
SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
if (sessionUser == null) {
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
if (sessionUser.getId() == Global.USER_TOP_ID) {
|
||||
json.set(2, "2-13");
|
||||
return json.toJson();
|
||||
}
|
||||
/*
|
||||
if (sessionUser.getUpid() != 0) {
|
||||
json.set(2, "2-13");
|
||||
return json.toJson();
|
||||
}
|
||||
*/
|
||||
ActivitySignVO signData = aSignService.getSignData(sessionUser.getId());
|
||||
if(signData != null) {
|
||||
json.data("data", signData);
|
||||
json.set(0, "0-1");
|
||||
} else {
|
||||
json.set(2, "2-4001");
|
||||
}
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>Title: ACTIVITY_SIGN_LOAD</p>
|
||||
* <p>Description: 用户参与签到活动</p>
|
||||
* @param session
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = WUC.ACTIVITY_SIGN, method = { RequestMethod.POST })
|
||||
@ResponseBody
|
||||
public Map<String, Object> ACTIVITY_SIGN(HttpSession session, HttpServletRequest request) {
|
||||
WebJSON json = new WebJSON(dataFactory);
|
||||
SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
if (sessionUser == null) {
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
if (sessionUser.getId() == Global.USER_TOP_ID) {
|
||||
json.set(2, "2-13");
|
||||
return json.toJson();
|
||||
}
|
||||
/*
|
||||
if (sessionUser.getUpid() != 0) {
|
||||
json.set(2, "2-13");
|
||||
return json.toJson();
|
||||
}
|
||||
*/
|
||||
double amount = aSignService.sign(json, sessionUser.getId());
|
||||
// amount < 0 签到失败并返回失败原因
|
||||
// amount == 0 签到成功
|
||||
// amount > 0 签到成功并成功领取金额
|
||||
if(amount >= 0) {
|
||||
int amountInt = new BigDecimal(amount).intValue();
|
||||
json.data("amount", amountInt);
|
||||
json.set(0, "0-1");
|
||||
}
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package activity.web.content;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.io.filefilter.FalseFileFilter;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
|
||||
import activity.domains.content.dao.ActivityRebateDao;
|
||||
import activity.domains.content.entity.ActivityRebate;
|
||||
import activity.domains.content.vo.activity.ActivityWheelVO;
|
||||
import javautils.http.HttpUtil;
|
||||
import javautils.math.MathUtil;
|
||||
import lottery.domains.content.biz.ActivityRebateWheelService;
|
||||
import lottery.domains.content.global.Global;
|
||||
import lottery.domains.pool.DataFactory;
|
||||
import lottery.web.WUC;
|
||||
import lottery.web.WebJSON;
|
||||
import lottery.web.helper.AbstractActionController;
|
||||
import lottery.web.helper.session.SessionUser;
|
||||
|
||||
/**
|
||||
* 幸运大转盘活动服务类
|
||||
* <p>Title: ActivityController</p>
|
||||
* <p>Description: </p>
|
||||
* @author James
|
||||
* @date 2018年2月3日
|
||||
*/
|
||||
@Controller
|
||||
public class WheelActivityController extends AbstractActionController {
|
||||
|
||||
@Autowired
|
||||
private ActivityRebateWheelService wheelService;
|
||||
|
||||
@Autowired
|
||||
private DataFactory dataFactory;
|
||||
|
||||
@Autowired
|
||||
private ActivityRebateDao aRebateDao;
|
||||
|
||||
/**
|
||||
* <p>Title: ACTIVITY_WHEEL_LOAD</p>
|
||||
* <p>Description:加载幸运大转盘活动信息 </p>
|
||||
* @param session
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = WUC.ACTIVITY_WHEEL_LOAD, method = { RequestMethod.POST })
|
||||
@ResponseBody
|
||||
public Map<String, Object> ACTIVITY_WHEEL_LOAD(HttpSession session, HttpServletRequest request) {
|
||||
WebJSON json = new WebJSON(dataFactory);
|
||||
SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
if (sessionUser == null) {
|
||||
return json.toJson();
|
||||
}
|
||||
if (sessionUser.getId() == Global.USER_TOP_ID) {
|
||||
json.set(2, "2-13");
|
||||
return json.toJson();
|
||||
}
|
||||
/*
|
||||
if (sessionUser.getUpid() != 0) {
|
||||
json.set(2, "2-13");
|
||||
return json.toJson();
|
||||
}
|
||||
*/
|
||||
ActivityWheelVO todayData = wheelService.getTodayData(sessionUser.getId());
|
||||
ActivityRebate rebate = aRebateDao.getById(Global.ACTIVITY_REBATE_WHEEL);
|
||||
if(todayData != null) {
|
||||
boolean enabled = true;
|
||||
if(rebate.getStatus() != 0) {
|
||||
enabled = false;
|
||||
}
|
||||
todayData.setEnabled(enabled);
|
||||
json.data("data", todayData);
|
||||
json.set(0, "0-1");
|
||||
} else {
|
||||
json.set(2, "2-4001");
|
||||
}
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* <p>Title: ACTIVITY_WHEEL_LOAD</p>
|
||||
* <p>Description:e用户参与幸运大转盘活动 </p>
|
||||
* @param session
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = WUC.ACTIVITY_WHEEL_DRAW, method = { RequestMethod.POST })
|
||||
@ResponseBody
|
||||
public Map<String, Object> ACTIVITY_WHEEL_DRAW(HttpSession session, HttpServletRequest request) {
|
||||
WebJSON json = new WebJSON(dataFactory);
|
||||
SessionUser sessionUser = super.getSessionUser(json, session, request);
|
||||
if (sessionUser == null) {
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
if (sessionUser.getId() == Global.USER_TOP_ID) {
|
||||
json.set(2, "2-13");
|
||||
return json.toJson();
|
||||
}
|
||||
/*
|
||||
if (sessionUser.getUpid() != 0) {
|
||||
json.set(2, "2-13");
|
||||
return json.toJson();
|
||||
}
|
||||
*/
|
||||
String ip = HttpUtil.getRealIp(json, request);
|
||||
if (ip == null) {
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
Double amount = wheelService.draw(json, sessionUser.getId(), ip);
|
||||
// amount == null || amount <= 0 活动参与失败并返回失败原因
|
||||
// amount > 0 活动参与成功并返回金额
|
||||
if(amount != null && amount > 0) {
|
||||
String amountStr = MathUtil.doubleUpTOString(amount);
|
||||
json.data("amount", amountStr);
|
||||
json.set(0, "0-1");
|
||||
}
|
||||
return json.toJson();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package javautils;
|
||||
|
||||
public class ObjectUtil {
|
||||
|
||||
public static double toDouble(Object object) {
|
||||
if(object != null && object instanceof Number) {
|
||||
return ((Number) object).doubleValue();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int toInt(Object object) {
|
||||
if(object != null && object instanceof Number) {
|
||||
return ((Number) object).intValue();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static long toLong(Object object) {
|
||||
if(object != null && object instanceof Number) {
|
||||
return ((Number) object).longValue();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static float toFloat(Object object) {
|
||||
if(object != null && object instanceof Number) {
|
||||
return ((Number) object).floatValue();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static short toShort(Object object) {
|
||||
if(object != null && object instanceof Number) {
|
||||
return ((Number) object).shortValue();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
package javautils;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.text.DecimalFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Random;
|
||||
|
||||
import javautils.date.Moment;
|
||||
import javautils.math.MathUtil;
|
||||
import javautils.regex.RegexUtil;
|
||||
|
||||
public class StringUtil {
|
||||
|
||||
/**
|
||||
* 判断字符串是否为空
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
public static boolean isNotNull(String s) {
|
||||
if(s == null) return false;
|
||||
if(s.trim().length() == 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符串能否转成int
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
public static boolean isInteger(String s) {
|
||||
try {
|
||||
Integer.parseInt(s);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符串能否转成double
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
public static boolean isDouble(String s) {
|
||||
try {
|
||||
Double.parseDouble(s);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符串能否转成float
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
public static boolean isFloat(String s) {
|
||||
try {
|
||||
Float.parseFloat(s);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符串能否转成boolean
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
public static boolean isBoolean(String s) {
|
||||
try {
|
||||
Boolean.parseBoolean(s);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断能否转成short
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
public static boolean isShort(String s) {
|
||||
try {
|
||||
Short.parseShort(s);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断能否转成long
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
public static boolean isLong(String s) {
|
||||
try {
|
||||
Long.parseLong(s);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动转类型
|
||||
* @param s
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
public static Object transObject(String s, Class<?> clazz) {
|
||||
if(clazz != null) {
|
||||
if(clazz == Integer.class) {
|
||||
if(isInteger(s)) {
|
||||
return Integer.parseInt(s);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(clazz == Double.class) {
|
||||
if(isDouble(s)) {
|
||||
return Double.parseDouble(s);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(clazz == Float.class) {
|
||||
if(isFloat(s)) {
|
||||
return Float.parseFloat(s);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(clazz == Boolean.class) {
|
||||
if(isBoolean(s)) {
|
||||
return Boolean.parseBoolean(s);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if(clazz == Short.class) {
|
||||
if(isShort(s)) {
|
||||
return Short.parseShort(s);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
if(clazz == Long.class) {
|
||||
if(isLong(s)) {
|
||||
return Long.parseLong(s);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
public static String transArrayToString(Object[] array) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (int i = 0, j = array.length; i < j; i++) {
|
||||
sb.append(array[i].toString());
|
||||
if(i < j - 1) {
|
||||
sb.append(",");
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String transArrayToString(Object[] array, String p) {
|
||||
String tempStr = new String();
|
||||
for (Object value : array) {
|
||||
tempStr += p + value.toString() + p + ",";
|
||||
}
|
||||
tempStr = tempStr.substring(0, tempStr.length() - 2);
|
||||
return tempStr;
|
||||
}
|
||||
|
||||
public static int[] transStringToIntArray(String string, String regex) {
|
||||
if (isNotNull(string)) {
|
||||
String[] sArray = string.split(regex);
|
||||
int[] intArray = new int[sArray.length];
|
||||
for (int i = 0; i < sArray.length; i++) {
|
||||
if(isIntegerString(sArray[i])) {
|
||||
intArray[i] = Integer.parseInt(sArray[i]);
|
||||
}
|
||||
}
|
||||
return intArray;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换文件大小
|
||||
* @param bytes
|
||||
* @return
|
||||
*/
|
||||
public static String transDataLong(long b) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
long KB = 1024;
|
||||
long MB = KB * 1024;
|
||||
long GB = MB * 1024;
|
||||
long TB = GB * 1024;
|
||||
if(b >= TB) {
|
||||
sb.append(MathUtil.doubleFormat((double)b/TB, 2) + "TB");
|
||||
} else if(b >= GB) {
|
||||
sb.append(MathUtil.doubleFormat((double)b/GB, 2) + "GB");
|
||||
} else if(b >= MB) {
|
||||
sb.append(MathUtil.doubleFormat((double)b/MB, 2) + "MB");
|
||||
} else if(b >= KB) {
|
||||
sb.append(MathUtil.doubleFormat((double)b/KB, 2) + "KB");
|
||||
} else {
|
||||
sb.append(b + "B");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 判断是否是int类型字符串
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static boolean isIntegerString(String str) {
|
||||
boolean flag = false;
|
||||
if(RegexUtil.isMatcher(str, RegexUtil.integer_regex)) {
|
||||
flag = true;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
public static boolean isDoubleString(String str) {
|
||||
boolean flag = false;
|
||||
if(RegexUtil.isMatcher(str, RegexUtil.rational_numbers_regex)) {
|
||||
flag = true;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
public static boolean isFloatString(String str) {
|
||||
boolean flag = false;
|
||||
if(RegexUtil.isMatcher(str, RegexUtil.rational_numbers_regex)) {
|
||||
flag = true;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符串是否是日期yyyy-MM-dd格式
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
public static boolean isDateString(String str) {
|
||||
try {
|
||||
if(str.length() != 10) {
|
||||
return false;
|
||||
}
|
||||
new SimpleDateFormat("yyyy-MM-dd").parse(str);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static String markWithSymbol(Object obj, String symbol) {
|
||||
return symbol + obj.toString() + symbol;
|
||||
}
|
||||
|
||||
//123456789
|
||||
public static Object[] split(String s) {
|
||||
char[] carr = s.toCharArray();
|
||||
Object[] arr = new Object[carr.length];
|
||||
for (int i = 0; i < carr.length; i++) {
|
||||
arr[i] = carr[i];
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public static String[] splitToString(String s) {
|
||||
char[] carr = s.toCharArray();
|
||||
String[] arr = new String[carr.length];
|
||||
for (int i = 0; i < carr.length; i++) {
|
||||
arr[i] = carr[i]+"";
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
public static String substring(String s, String start, String end, boolean isInSub) {
|
||||
int idx = s.indexOf(start);
|
||||
int edx = s.indexOf(end);
|
||||
idx = idx == -1 ? 0 : idx + (isInSub ? 0 : start.length());
|
||||
edx = edx == -1 ? s.length() : edx + (isInSub ? end.length() : 0);
|
||||
return s.substring(idx, edx);
|
||||
}
|
||||
|
||||
public static String doubleFormat(double d) {
|
||||
DecimalFormat decimalformat = new DecimalFormat("#0.00");
|
||||
return decimalformat.format(d);
|
||||
}
|
||||
|
||||
public static String fromInputStream(InputStream inputStream) {
|
||||
try {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
byte[] bytes = new byte[1024];
|
||||
int len;
|
||||
while ((len = inputStream.read(bytes)) != -1) {
|
||||
sb.append(new String(bytes, 0, len));
|
||||
}
|
||||
inputStream.close();
|
||||
return sb.toString();
|
||||
} catch (Exception e) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证是否是服务时间
|
||||
* @param moment
|
||||
* @param times 格式为12:00~2:00
|
||||
* @return
|
||||
*/
|
||||
public static boolean isServiceTime(Moment moment, String times) {
|
||||
int thisMins = moment.hour() * 60 + moment.minute();
|
||||
String[] timeArr = times.split("~");
|
||||
int startMins = Integer.parseInt(timeArr[0].split(":")[0]) * 60 + Integer.parseInt(timeArr[0].split(":")[1]);
|
||||
int endMins = Integer.parseInt(timeArr[1].split(":")[0]) * 60 + Integer.parseInt(timeArr[1].split(":")[1]);
|
||||
if(startMins < endMins) {
|
||||
// 不在服务内的时间是 0 - start 和 end - 24
|
||||
if((thisMins > 0 && thisMins < startMins) || (thisMins > endMins && thisMins < 24 * 60)) {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// 不在服务内的时间是 end - start
|
||||
if(thisMins > endMins && thisMins < startMins) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定长度�?-9A-Za-z随机字符�?说明:随机长度小于等于零时默�?6
|
||||
*
|
||||
* @param getLength
|
||||
* @return
|
||||
*/
|
||||
public static String getRandomString(int getLength) {
|
||||
int StringLength = 16;
|
||||
if (getLength > 0) {
|
||||
StringLength = getLength;
|
||||
}
|
||||
int[] number = {48, 49, 50, 51, 52, 53, 54, 55, 56, 57};// 定义数字数组
|
||||
int[] lAlphabet = {65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85,
|
||||
86, 87, 88, 89, 90};// 定义小写字母数组
|
||||
int[] tAlphabet = {97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113,
|
||||
114, 115, 116, 117, 118, 119, 120, 121, 122};// 定义大小字母数组
|
||||
Random rd = new Random();
|
||||
int nowNum = 0;
|
||||
StringBuffer nowString = new StringBuffer();
|
||||
for (int j = 0; j < StringLength; j++) {
|
||||
nowNum = rd.nextInt(3);
|
||||
switch (nowNum) {
|
||||
case 0:
|
||||
nowString.append((char) number[rd.nextInt(number.length)]);
|
||||
break;
|
||||
case 1:
|
||||
nowString.append((char) lAlphabet[rd.nextInt(lAlphabet.length)]);
|
||||
break;
|
||||
case 2:
|
||||
nowString.append((char) tAlphabet[rd.nextInt(tAlphabet.length)]);
|
||||
break;
|
||||
default:
|
||||
nowString.append((char) lAlphabet[rd.nextInt(lAlphabet.length)]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return nowString.toString();
|
||||
}
|
||||
|
||||
//姓名只能包含中文
|
||||
public static boolean isNameChn(String name){
|
||||
return name.matches(RegexUtil.name_input_chn);
|
||||
//
|
||||
// boolean result = true;
|
||||
// int num = 0;
|
||||
// for(int i=0;i<name.length();i++){
|
||||
// if(!Pattern.matches(RegexUtil.name_input_chn, name.substring(i, i + 1))){
|
||||
// num++;
|
||||
// }
|
||||
// }
|
||||
// if(num > 0){
|
||||
// result = false;
|
||||
// }
|
||||
// return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package javautils.activity;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import activity.domains.content.vo.activity.ActivityCostInfoVo;
|
||||
import net.sf.json.JSONArray;
|
||||
import net.sf.json.JSONObject;
|
||||
|
||||
public class PrizeUtils {
|
||||
/**
|
||||
* 根据消费额拿的活动配置对应的消费奖励
|
||||
* @param res
|
||||
* @param costMoney
|
||||
* @return
|
||||
*/
|
||||
public static double costConfigPrize(String res,double costMoney){
|
||||
double darwMoney = 0;
|
||||
JSONArray jsonArray = JSONArray.fromObject(res);
|
||||
for (int i = 0; i < jsonArray.size(); i++) {
|
||||
JSONObject obj = JSONObject.fromObject(String.valueOf(jsonArray.get(i)));
|
||||
double cost = Double.parseDouble(String.valueOf(obj.get("cost")));
|
||||
double prizeMoney = Double.parseDouble(String.valueOf(obj.get("prizeMoney")));
|
||||
if(costMoney >= cost && prizeMoney > darwMoney){
|
||||
darwMoney = prizeMoney;
|
||||
}
|
||||
}
|
||||
return darwMoney;
|
||||
}
|
||||
|
||||
public static List<ActivityCostInfoVo> costConfigInfo(String res){
|
||||
JSONArray jsonArray = JSONArray.fromObject(res);
|
||||
List<ActivityCostInfoVo> listvo = new ArrayList<ActivityCostInfoVo>();
|
||||
for (int i = 0; i < jsonArray.size(); i++) {
|
||||
ActivityCostInfoVo cost = new ActivityCostInfoVo();
|
||||
JSONObject obj = JSONObject.fromObject(String.valueOf(jsonArray.get(i)));
|
||||
cost.setCost(Double.parseDouble(String.valueOf(obj.get("cost"))));
|
||||
cost.setPrizeMoney(Double.parseDouble(String.valueOf(obj.get("prizeMoney"))));
|
||||
listvo.add(cost);
|
||||
}
|
||||
return listvo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
package javautils.array;
|
||||
|
||||
import javautils.StringUtil;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ArrayUtils {
|
||||
|
||||
/**
|
||||
* 针对数据库in
|
||||
* @param ids
|
||||
* @return
|
||||
*/
|
||||
public static String transInIds(int[] ids) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (int i = 0, j = ids.length; i < j; i++) {
|
||||
sb.append(ids[i]);
|
||||
if(i < j - 1) {
|
||||
sb.append(",");
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String transInIds(Integer[] ids) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (int i = 0, j = ids.length; i < j; i++) {
|
||||
sb.append(ids[i].intValue());
|
||||
if(i < j - 1) {
|
||||
sb.append(",");
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 针对数据库in
|
||||
* @param ids
|
||||
* @return
|
||||
*/
|
||||
public static String transInIds(List<Integer> ids) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (int i = 0, j = ids.size(); i < j; i++) {
|
||||
sb.append(ids.get(i).intValue());
|
||||
if(i < j - 1) {
|
||||
sb.append(",");
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static List<Integer> transStrToInteger(List<String> ids) {
|
||||
if (ids == null || ids.size() <= 0) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
List<Integer> arr = new ArrayList<>(ids.size());
|
||||
for (int i = 0; i < ids.size(); i++) {
|
||||
arr.add(Integer.valueOf(ids.get(i)));
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除某个id
|
||||
* @param ids
|
||||
* @return
|
||||
*/
|
||||
public static String deleteInsertIds(String ids, int id, boolean isAll) {
|
||||
if(StringUtil.isNotNull(ids)) {
|
||||
if(ids.indexOf("[" + id + "]") != -1) {
|
||||
String[] tmp = ids.replaceAll("\\[|\\]", "").split(",");
|
||||
List<Integer> list = new ArrayList<>();
|
||||
for (int i = 0; i < tmp.length; i++) {
|
||||
if(id != Integer.parseInt(tmp[i])) {
|
||||
list.add(Integer.parseInt(tmp[i]));
|
||||
} else {
|
||||
if(isAll) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
int[] arr = new int[list.size()];
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
arr[i] = list.get(i);
|
||||
}
|
||||
return transInsertIds(arr);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* 存进数据库
|
||||
* @param ids
|
||||
* @return
|
||||
*/
|
||||
public static String transInsertIds(int[] ids) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (int i = 0, j = ids.length; i < j; i++) {
|
||||
sb.append("[" + ids[i] + "]");
|
||||
if(i < j - 1) {
|
||||
sb.append(",");
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取id的时候,解析成id数组
|
||||
* @param ids
|
||||
* @return
|
||||
*/
|
||||
public static int[] transGetIds(String ids) {
|
||||
String[] tmp = ids.replaceAll("\\[|\\]", "").split(",");
|
||||
int[] arr = new int[tmp.length];
|
||||
for (int i = 0; i < arr.length; i++) {
|
||||
arr[i] = Integer.parseInt(tmp[i]);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取id的时候,解析成id数组
|
||||
* @param ids
|
||||
* @return
|
||||
*/
|
||||
public static Integer[] transGetIdsToInteger(String ids) {
|
||||
String[] tmp = ids.replaceAll("\\[|\\]", "").split(",");
|
||||
Integer[] arr = new Integer[tmp.length];
|
||||
for (int i = 0; i < arr.length; i++) {
|
||||
arr[i] = Integer.parseInt(tmp[i]);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换成字符串
|
||||
* @param list
|
||||
* @return
|
||||
*/
|
||||
public static String toString(List<Integer> list) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (int i = 0, j = list.size(); i < j; i++) {
|
||||
sb.append(list.get(i));
|
||||
if(i < j - 1) {
|
||||
sb.append(",");
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换成字符串
|
||||
* @return
|
||||
*/
|
||||
public static String toStringFromSet(java.util.Set<String> set) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
int count = 0;
|
||||
for (String str : set) {
|
||||
sb.append(str);
|
||||
if(count < set.size() - 1) {
|
||||
sb.append(",");
|
||||
}
|
||||
count++;
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static int[] listToInt(List<Integer> list) {
|
||||
int[] arr = new int[list.size()];
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
arr[i] = list.get(i);
|
||||
}
|
||||
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* 快速排序<br>
|
||||
* 算法的思想在于分而治之:先找一个元素(一般来说都是数组头元素),把比它大的都放到右边,把比它小的都放到左边;<br>
|
||||
* 然后再按照这样的思想去处理两个子数组; 下面说的子数组头元素通指用来划分数组的元素;<br>
|
||||
* <br>
|
||||
* 下面程序关键点就在于!forward, low0++, high0--这些运算; 这三个运算使得a[low0],a[high0]里面总有一个指向子数组头元素; <br>
|
||||
* 可以用极端的情况来方便理解这三个值的运作: <br>
|
||||
* 假如我的数列为0123456789, 初始时forward=false,0作为子数组划分依据,很显然第一轮的时候不会发生任何交换,low0一直指向0,<br>
|
||||
* high0逐渐下降直到它指向0为止; 同理可思考9876543210这个例子;<br>
|
||||
* <br>
|
||||
* 时间复杂度: 平均:O(nlogn),最好:O(nlogn);最坏:O(n^2);
|
||||
* 空间复杂度: O(logn);要为递归栈提供空间
|
||||
* @param a 待排序数组<br>
|
||||
* @param low 子数组开始的下标;<br>
|
||||
* @param high 子数组结束的下标;<br>
|
||||
*/
|
||||
public static void quickSortDouble(double[] a, int low, int high){
|
||||
if(low>=high){
|
||||
return;
|
||||
}
|
||||
int low0 = low;
|
||||
int high0 = high;
|
||||
boolean forward = false;
|
||||
while(low0!=high0){
|
||||
if(a[low0]>a[high0]){
|
||||
double tmp = a[low0];
|
||||
a[low0] = a[high0];
|
||||
a[high0] = tmp;
|
||||
forward = !forward;
|
||||
}
|
||||
if(forward){
|
||||
low0++;
|
||||
}
|
||||
else{
|
||||
high0--;
|
||||
}
|
||||
}
|
||||
low0--;
|
||||
high0++;
|
||||
quickSortDouble(a, low, low0);
|
||||
quickSortDouble(a, high0, high);
|
||||
}
|
||||
|
||||
/**
|
||||
* 快速排序的简单调用形式<br>
|
||||
* 方便测试和调用<br>
|
||||
* @param a
|
||||
*/
|
||||
public static void quickSortDouble(double[] a){
|
||||
quickSortDouble(a, 0, a.length-1);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 快速排序<br>
|
||||
* 算法的思想在于分而治之:先找一个元素(一般来说都是数组头元素),把比它大的都放到右边,把比它小的都放到左边;<br>
|
||||
* 然后再按照这样的思想去处理两个子数组; 下面说的子数组头元素通指用来划分数组的元素;<br>
|
||||
* <br>
|
||||
* 下面程序关键点就在于!forward, low0++, high0--这些运算; 这三个运算使得a[low0],a[high0]里面总有一个指向子数组头元素; <br>
|
||||
* 可以用极端的情况来方便理解这三个值的运作: <br>
|
||||
* 假如我的数列为0123456789, 初始时forward=false,0作为子数组划分依据,很显然第一轮的时候不会发生任何交换,low0一直指向0,<br>
|
||||
* high0逐渐下降直到它指向0为止; 同理可思考9876543210这个例子;<br>
|
||||
* <br>
|
||||
* 时间复杂度: 平均:O(nlogn),最好:O(nlogn);最坏:O(n^2);
|
||||
* 空间复杂度: O(logn);要为递归栈提供空间
|
||||
* @param a 待排序数组<br>
|
||||
* @param low 子数组开始的下标;<br>
|
||||
* @param high 子数组结束的下标;<br>
|
||||
*/
|
||||
public static void quickSortString(String[] a, int low, int high){
|
||||
if(low>=high){
|
||||
return;
|
||||
}
|
||||
int low0 = low;
|
||||
int high0 = high;
|
||||
boolean forward = false;
|
||||
while(low0!=high0){
|
||||
if(a[low0].compareTo(a[high0]) > 0){
|
||||
String tmp = a[low0];
|
||||
a[low0] = a[high0];
|
||||
a[high0] = tmp;
|
||||
forward = !forward;
|
||||
}
|
||||
if(forward){
|
||||
low0++;
|
||||
}
|
||||
else{
|
||||
high0--;
|
||||
}
|
||||
}
|
||||
low0--;
|
||||
high0++;
|
||||
quickSortString(a, low, low0);
|
||||
quickSortString(a, high0, high);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String str = deleteInsertIds("[418],[243],[199],[72]", 243, true);
|
||||
System.out.println(str);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package javautils.datasource;
|
||||
|
||||
import com.alibaba.druid.filter.logging.Log4jFilter;
|
||||
import com.alibaba.druid.filter.stat.StatFilter;
|
||||
import com.alibaba.druid.wall.WallFilter;
|
||||
|
||||
/**
|
||||
* Created by Nick on 2016/07/06
|
||||
*/
|
||||
public class ConfigDruidDataSource {
|
||||
/**
|
||||
* 日志
|
||||
*/
|
||||
public static Log4jFilter configLog4jFilter() {
|
||||
Log4jFilter filter = new Log4jFilter();
|
||||
filter.setStatementExecuteQueryAfterLogEnabled(false);
|
||||
filter.setStatementExecuteUpdateAfterLogEnabled(false);
|
||||
filter.setStatementExecuteBatchAfterLogEnabled(false);
|
||||
filter.setStatementExecuteAfterLogEnabled(false);
|
||||
filter.setStatementExecutableSqlLogEnable(false);
|
||||
filter.setStatementParameterSetLogEnabled(false);
|
||||
filter.setStatementParameterClearLogEnable(false);
|
||||
filter.setStatementCreateAfterLogEnabled(false);
|
||||
filter.setStatementCloseAfterLogEnabled(false);
|
||||
filter.setStatementPrepareAfterLogEnabled(false);
|
||||
filter.setStatementPrepareCallAfterLogEnabled(false);
|
||||
filter.setStatementLogEnabled(false);
|
||||
filter.setStatementLogErrorEnabled(false);
|
||||
return filter;
|
||||
}
|
||||
|
||||
/**
|
||||
* sql过滤
|
||||
*/
|
||||
public static StatFilter configStatFilter() {
|
||||
StatFilter filter = new StatFilter();
|
||||
filter.setSlowSqlMillis(5000);
|
||||
filter.setLogSlowSql(true);
|
||||
filter.setMergeSql(true);
|
||||
return filter;
|
||||
}
|
||||
|
||||
// /**
|
||||
// * 防sql注入
|
||||
// */
|
||||
// public static WallFilter configWallFilter() {
|
||||
// WallFilter filter = new WallFilter();
|
||||
// filter.getConfig().setallow
|
||||
// return filter;
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package javautils.datasource;
|
||||
|
||||
import com.alibaba.druid.filter.Filter;
|
||||
import com.alibaba.druid.pool.DruidDataSource;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Created by Nick on 2016/07/06
|
||||
*/
|
||||
public class CustomDruidDataSource extends DruidDataSource {
|
||||
@Override
|
||||
public List<Filter> getProxyFilters() {
|
||||
List<Filter> proxyFilters = new ArrayList<>();
|
||||
proxyFilters.add(ConfigDruidDataSource.configLog4jFilter());
|
||||
proxyFilters.add(ConfigDruidDataSource.configStatFilter());
|
||||
return proxyFilters;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package javautils.datasource;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.aspectj.lang.JoinPoint;
|
||||
import org.aspectj.lang.Signature;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
|
||||
import org.springframework.transaction.interceptor.TransactionAttribute;
|
||||
import org.springframework.transaction.interceptor.TransactionAttributeSource;
|
||||
import org.springframework.transaction.interceptor.TransactionInterceptor;
|
||||
import org.springframework.util.PatternMatchUtils;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 定义数据源的AOP切面,该类控制了使用Master还是Slave。
|
||||
*
|
||||
* 如果事务管理中配置了事务策略,则采用配置的事务策略中的标记了ReadOnly的方法是用Slave,其它使用Master。
|
||||
*
|
||||
* 如果没有配置事务管理的策略,则采用方法名匹配的原则,以query、find、get开头方法用Slave,其它用Master。
|
||||
*
|
||||
* @author zhijun
|
||||
*
|
||||
*/
|
||||
public class DataSourceAspect {
|
||||
|
||||
private List<String> slaveMethodPattern = new ArrayList<>();
|
||||
|
||||
private static final String[] defaultSlaveMethodStart = new String[]{ "query", "find", "get", "list"};
|
||||
|
||||
private String[] slaveMethodStart;
|
||||
|
||||
/**
|
||||
* 读取事务管理中的策略
|
||||
*
|
||||
* @param txAdvice
|
||||
* @throws Exception
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public void setTxAdvice(TransactionInterceptor txAdvice) throws Exception {
|
||||
if (txAdvice == null) {
|
||||
// 没有配置事务管理策略
|
||||
return;
|
||||
}
|
||||
//从txAdvice获取到策略配置信息
|
||||
TransactionAttributeSource transactionAttributeSource = txAdvice.getTransactionAttributeSource();
|
||||
if (!(transactionAttributeSource instanceof NameMatchTransactionAttributeSource)) {
|
||||
return;
|
||||
}
|
||||
//使用反射技术获取到NameMatchTransactionAttributeSource对象中的nameMap属性值
|
||||
NameMatchTransactionAttributeSource matchTransactionAttributeSource = (NameMatchTransactionAttributeSource) transactionAttributeSource;
|
||||
Field nameMapField = ReflectionUtils.findField(NameMatchTransactionAttributeSource.class, "nameMap");
|
||||
nameMapField.setAccessible(true); //设置该字段可访问
|
||||
//获取nameMap的值
|
||||
Map<String, TransactionAttribute> map = (Map<String, TransactionAttribute>) nameMapField.get(matchTransactionAttributeSource);
|
||||
|
||||
//遍历nameMap
|
||||
for (Map.Entry<String, TransactionAttribute> entry : map.entrySet()) {
|
||||
if (!entry.getValue().isReadOnly()) {//判断之后定义了ReadOnly的策略才加入到slaveMethodPattern
|
||||
continue;
|
||||
}
|
||||
slaveMethodPattern.add(entry.getKey());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 在进入Service方法之前执行
|
||||
*
|
||||
* @param point 切面对象
|
||||
*/
|
||||
public void before(JoinPoint point) {
|
||||
// 获取到当前执行的方法名
|
||||
String methodName = point.getSignature().getName();
|
||||
|
||||
Signature signature = point.getSignature();
|
||||
MethodSignature methodSignature = (MethodSignature) signature;
|
||||
Method method = methodSignature.getMethod();
|
||||
|
||||
boolean isSlave = false;
|
||||
|
||||
ForceMaster forceMaster = method.getAnnotation(ForceMaster.class);
|
||||
ForceSlave forceSlave = method.getAnnotation(ForceSlave.class);
|
||||
if (forceMaster != null) {
|
||||
isSlave = false;
|
||||
}
|
||||
else if (forceSlave != null) {
|
||||
isSlave = true;
|
||||
}
|
||||
else {
|
||||
if (slaveMethodPattern.isEmpty()) {
|
||||
// 当前Spring容器中没有配置事务策略,采用方法名匹配方式
|
||||
isSlave = isSlave(methodName);
|
||||
} else {
|
||||
// 使用策略规则匹配
|
||||
for (String mappedName : slaveMethodPattern) {
|
||||
if (isMatch(methodName, mappedName)) {
|
||||
isSlave = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isSlave) {
|
||||
// 标记为读库
|
||||
DynamicDataSourceHolder.markSlave();
|
||||
} else {
|
||||
// 标记为写库
|
||||
DynamicDataSourceHolder.markMaster();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为读库
|
||||
*
|
||||
* @param methodName
|
||||
* @return
|
||||
*/
|
||||
private Boolean isSlave(String methodName) {
|
||||
// 方法名以query、find、get开头的方法名走从库
|
||||
return StringUtils.startsWithAny(methodName, getSlaveMethodStart());
|
||||
}
|
||||
|
||||
/**
|
||||
* 通配符匹配
|
||||
*
|
||||
* Return if the given method name matches the mapped name.
|
||||
* <p>
|
||||
* The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, as well as direct
|
||||
* equality. Can be overridden in subclasses.
|
||||
*
|
||||
* @param methodName the method name of the class
|
||||
* @param mappedName the name in the descriptor
|
||||
* @return if the names match
|
||||
* @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
|
||||
*/
|
||||
protected boolean isMatch(String methodName, String mappedName) {
|
||||
return PatternMatchUtils.simpleMatch(mappedName, methodName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户指定slave的方法名前缀
|
||||
* @param slaveMethodStart
|
||||
*/
|
||||
public void setSlaveMethodStart(String[] slaveMethodStart) {
|
||||
this.slaveMethodStart = slaveMethodStart;
|
||||
}
|
||||
|
||||
public String[] getSlaveMethodStart() {
|
||||
if(this.slaveMethodStart == null){
|
||||
// 没有指定,使用默认
|
||||
return defaultSlaveMethodStart;
|
||||
}
|
||||
return slaveMethodStart;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package javautils.datasource;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* 定义动态数据源,实现通过集成Spring提供的AbstractRoutingDataSource,只需要实现determineCurrentLookupKey方法即可
|
||||
*
|
||||
* 由于DynamicDataSource是单例的,线程不安全的,所以采用ThreadLocal保证线程安全,由DynamicDataSourceHolder完成。
|
||||
*
|
||||
* @author zhijun
|
||||
*
|
||||
*/
|
||||
public class DynamicDataSource extends AbstractRoutingDataSource{
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSource.class);
|
||||
|
||||
private Integer slaveCount;
|
||||
|
||||
// 轮询计数,初始为-1,AtomicInteger是线程安全的
|
||||
private AtomicInteger counter = new AtomicInteger(-1);
|
||||
|
||||
// 记录读库的key
|
||||
private List<Object> slaveDataSources = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
protected Object determineCurrentLookupKey() {
|
||||
// 使用DynamicDataSourceHolder保证线程安全,并且得到当前线程中的数据源key
|
||||
if (DynamicDataSourceHolder.isMaster()) {
|
||||
Object key = DynamicDataSourceHolder.getDataSourceKey();
|
||||
if (LOGGER.isDebugEnabled()) {
|
||||
LOGGER.debug("当前DataSource的key为: " + key);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
Object key = getSlaveKey();
|
||||
if (LOGGER.isDebugEnabled()) {
|
||||
LOGGER.debug("当前DataSource的key为: " + key);
|
||||
}
|
||||
return key;
|
||||
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
super.afterPropertiesSet();
|
||||
|
||||
// 由于父类的resolvedDataSources属性是私有的子类获取不到,需要使用反射获取
|
||||
Field field = ReflectionUtils.findField(AbstractRoutingDataSource.class, "resolvedDataSources");
|
||||
field.setAccessible(true); // 设置可访问
|
||||
|
||||
try {
|
||||
Map<Object, DataSource> resolvedDataSources = (Map<Object, DataSource>) field.get(this);
|
||||
// 读库的数据量等于数据源总数减去写库的数量
|
||||
this.slaveCount = resolvedDataSources.size() - 1;
|
||||
for (Map.Entry<Object, DataSource> entry : resolvedDataSources.entrySet()) {
|
||||
if (DynamicDataSourceHolder.MASTER.equals(entry.getKey())) {
|
||||
continue;
|
||||
}
|
||||
slaveDataSources.add(entry.getKey());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("afterPropertiesSet error! ", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询算法实现
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public Object getSlaveKey() {
|
||||
// 得到的下标为:0、1、2、3……
|
||||
Integer index = counter.incrementAndGet() % slaveCount;
|
||||
if (counter.get() > 9999) { // 以免超出Integer范围
|
||||
counter.set(-1); // 还原
|
||||
}
|
||||
return slaveDataSources.get(index);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package javautils.datasource;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
/*
|
||||
* 使用ThreadLocal技术来记录当前线程中的数据源的key
|
||||
*
|
||||
* @author zhijun
|
||||
*
|
||||
*/
|
||||
public class DynamicDataSourceHolder {
|
||||
|
||||
//写库对应的数据源key
|
||||
public static final String MASTER = "master";
|
||||
|
||||
//读库对应的数据源key
|
||||
public static final String SLAVE = "slave";
|
||||
|
||||
//使用ThreadLocal记录当前线程的数据源key
|
||||
private static final ThreadLocal<String> holder = new ThreadLocal<>();
|
||||
|
||||
/**
|
||||
* 设置数据源key
|
||||
* @param key
|
||||
*/
|
||||
public static void putDataSourceKey(String key) {
|
||||
holder.set(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据源key
|
||||
* @return
|
||||
*/
|
||||
public static String getDataSourceKey() {
|
||||
return holder.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记写库
|
||||
*/
|
||||
public static void markMaster(){
|
||||
putDataSourceKey(MASTER);
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记读库
|
||||
*/
|
||||
public static void markSlave(){
|
||||
putDataSourceKey(SLAVE);
|
||||
}
|
||||
|
||||
public static boolean isMaster() {
|
||||
String current = holder.get();
|
||||
return StringUtils.isNotEmpty(current) && MASTER.equals(current);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package javautils.datasource;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 强制读写分离策略使用主库
|
||||
* Created by Nick on 2017-06-02.
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface ForceMaster {
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package javautils.datasource;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 强制读写分离策略使用从库
|
||||
* Created by Nick on 2017-06-02.
|
||||
*/
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface ForceSlave {
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package javautils.date;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 依赖于Moment.java
|
||||
*/
|
||||
public class DateRangeUtil {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String[] days = listDate("2014-01-01", "2014-01-15");
|
||||
for (String string : days) {
|
||||
System.out.println(string);
|
||||
}
|
||||
}
|
||||
|
||||
public static String[] listDate(String sDate, String eDate) {
|
||||
Moment sMoment = new Moment().fromDate(sDate);
|
||||
Moment eMoment = new Moment().fromDate(eDate);
|
||||
List<String> list = new ArrayList<>();
|
||||
if(sMoment.le(eMoment)) {
|
||||
list.add(sMoment.toSimpleDate());
|
||||
int days = eMoment.difference(sMoment, "day");
|
||||
for (int i = 0; i < days - 1; i++) {
|
||||
list.add(sMoment.add(1, "days").toSimpleDate());
|
||||
}
|
||||
}
|
||||
String[] array = new String[list.size()];
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
array[i] = list.get(i);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
public static String[] listDateWithLastDay(String sDate, String eDate) {
|
||||
Moment sMoment = new Moment().fromDate(sDate);
|
||||
Moment eMoment = new Moment().fromDate(eDate);
|
||||
List<String> list = new ArrayList<>();
|
||||
if(sMoment.le(eMoment)) {
|
||||
list.add(sMoment.toSimpleDate());
|
||||
int days = eMoment.difference(sMoment, "day");
|
||||
for (int i = 0; i < days; i++) {
|
||||
list.add(sMoment.add(1, "days").toSimpleDate());
|
||||
}
|
||||
}
|
||||
String[] array = new String[list.size()];
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
array[i] = list.get(i);
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,436 @@
|
||||
package javautils.date;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
public class DateUtil {
|
||||
|
||||
/**
|
||||
* 获取当前时间
|
||||
* @return
|
||||
*/
|
||||
public static String getCurrentTime() {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
return dateToString(g);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前日期
|
||||
* @return
|
||||
*/
|
||||
public static String getCurrentDate() {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
return dateToStringSim(g);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取昨天日期
|
||||
* @return
|
||||
*/
|
||||
public static String getYesterday() {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
g.set(Calendar.DATE, g.get(Calendar.DATE) - 1);
|
||||
return dateToStringSim(g);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取明天日期
|
||||
* @return
|
||||
*/
|
||||
public static String getToday() {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
g.set(Calendar.DATE, g.get(Calendar.DATE));
|
||||
return dateToStringSim(g);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取明天日期
|
||||
* @return
|
||||
*/
|
||||
public static String getTomorrow() {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
g.set(Calendar.DATE, g.get(Calendar.DATE) + 1);
|
||||
return dateToStringSim(g);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换成时间
|
||||
* @param ms
|
||||
* @return
|
||||
*/
|
||||
public static String getTime(long ms) {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
g.setTimeInMillis(ms);
|
||||
return dateToString(g);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据时间获取GregorianCalendar
|
||||
* @param time
|
||||
* @return
|
||||
*/
|
||||
private static GregorianCalendar getCalendarByTime(String time, String format) {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
try {
|
||||
g.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time));
|
||||
} catch (ParseException e) {
|
||||
g = null;
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算时间
|
||||
* @param g
|
||||
* @param seconds
|
||||
* @return
|
||||
*/
|
||||
private static String calcDate(GregorianCalendar g, int seconds) {
|
||||
if(g == null) {
|
||||
g = new GregorianCalendar();
|
||||
}
|
||||
g.add(Calendar.SECOND, seconds);
|
||||
return dateToString(g);
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期转字符串
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static String dateToString(Date date) {
|
||||
try {
|
||||
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
|
||||
String s = formatter.format(date);
|
||||
return s;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转日期
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static Date stringToDate(String date) {
|
||||
try {
|
||||
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Date d = (Date) formatter.parse(date);
|
||||
return d;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转日期, 自定义格式
|
||||
* @param date
|
||||
* @param format
|
||||
* @return
|
||||
*/
|
||||
public static Date stringToDate(String date, String format) {
|
||||
try {
|
||||
DateFormat formatter = new SimpleDateFormat(format);
|
||||
Date d = (Date) formatter.parse(date);
|
||||
return d;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取日期相差毫秒数
|
||||
* @param subDate
|
||||
* @param minDate
|
||||
* @return
|
||||
*/
|
||||
public static long calcDate(String subDate, String minDate) {
|
||||
long lSubDate = getCalendarByTime(subDate, "yyyy-MM-dd HH:mm:ss").getTimeInMillis();
|
||||
long lMinDate = getCalendarByTime(minDate, "yyyy-MM-dd HH:mm:ss").getTimeInMillis();
|
||||
return (lSubDate - lMinDate);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据日期计算相差天数,忽略时分秒
|
||||
* @param date1
|
||||
* @param date2
|
||||
* @return
|
||||
*/
|
||||
public static int calcDays(Date date1, Date date2) {
|
||||
Calendar date1Calendar = Calendar.getInstance();
|
||||
date1Calendar.setTime(date1);
|
||||
|
||||
Calendar date2Calendar = Calendar.getInstance();
|
||||
date2Calendar.setTime(date2);
|
||||
|
||||
int day1 = date1Calendar.get(Calendar.DAY_OF_YEAR);
|
||||
int day2 = date2Calendar.get(Calendar.DAY_OF_YEAR);
|
||||
|
||||
return day1 - day2;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据差值计算出新的时间
|
||||
* @param time
|
||||
* @param seconds
|
||||
* @return
|
||||
*/
|
||||
public static String calcDateByTime(String time, int seconds) {
|
||||
GregorianCalendar g = getCalendarByTime(time, "yyyy-MM-dd HH:mm:ss");
|
||||
return calcDate(g, seconds);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据天数计算出新的日期
|
||||
* @param date
|
||||
* @param days
|
||||
* @return
|
||||
*/
|
||||
public static String calcNewDay(String date, int days) {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
g.setTimeInMillis(formatTime(date, "yyyy-MM-dd"));
|
||||
g.set(Calendar.DATE, g.get(Calendar.DATE) + days);
|
||||
return dateToStringSim(g);
|
||||
}
|
||||
|
||||
/**
|
||||
* 下一天
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static String calcNextDay(String date) {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
g.setTimeInMillis(formatTime(date, "yyyy-MM-dd"));
|
||||
g.set(Calendar.DATE, g.get(Calendar.DATE) + 1);
|
||||
return dateToStringSim(g);
|
||||
}
|
||||
|
||||
/**
|
||||
* 上一天
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static String calcLastDay(String date) {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
g.setTimeInMillis(formatTime(date, "yyyy-MM-dd"));
|
||||
g.set(Calendar.DATE, g.get(Calendar.DATE) - 1);
|
||||
return dateToStringSim(g);
|
||||
}
|
||||
|
||||
private static Calendar getDateOfMonth(Calendar date, int num, boolean flag) {
|
||||
Calendar lastDate = (Calendar) date.clone();
|
||||
if(flag) {
|
||||
lastDate.add(Calendar.MONTH, num);
|
||||
}else {
|
||||
lastDate.add(Calendar.MONTH, -num);
|
||||
}
|
||||
|
||||
return lastDate;
|
||||
}
|
||||
|
||||
private static Calendar getDateOfLastMonth(String dateStr, int num, boolean flag) {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
try {
|
||||
Date date = sdf.parse(dateStr);
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTime(date);
|
||||
return getDateOfMonth(c, num, flag);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid date format(yyyyMMdd): " + dateStr);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取上个月的同一天
|
||||
* @param date
|
||||
* @param num
|
||||
* @param flag
|
||||
* @return
|
||||
*/
|
||||
public static String getSameDateOfLastMonth(String date, int num, boolean flag) {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
|
||||
String lastDate = sdf.format(getDateOfLastMonth(date, num, flag).getTime());
|
||||
return lastDate;
|
||||
}
|
||||
|
||||
/**
|
||||
* GregorianCalendar转成字符串
|
||||
* @param g
|
||||
* @return
|
||||
*/
|
||||
private static String dateToString(GregorianCalendar g) {
|
||||
String year = String.valueOf(g.get(Calendar.YEAR));
|
||||
String month = String.format("%02d", g.get(Calendar.MONTH) + 1);
|
||||
String day =String.format("%02d", g.get(Calendar.DAY_OF_MONTH));
|
||||
String hours = String.format("%02d", g.get(Calendar.HOUR_OF_DAY));
|
||||
String minutes = String.format("%02d", g.get(Calendar.MINUTE));
|
||||
String seconds = String.format("%02d", g.get(Calendar.SECOND));
|
||||
return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据时间转成MS
|
||||
* @param time
|
||||
* @param format
|
||||
* @return
|
||||
*/
|
||||
public static long stringToLong(String time, String format) {
|
||||
return stringToDate(time, format).getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* GregorianCalendar转成日期格式
|
||||
* @param g
|
||||
* @return
|
||||
*/
|
||||
public static String dateToStringSim(GregorianCalendar g) {
|
||||
String year = String.valueOf(g.get(Calendar.YEAR));
|
||||
String month = String.format("%02d", g.get(Calendar.MONTH) + 1);
|
||||
String day = String.format("%02d", g.get(Calendar.DAY_OF_MONTH));
|
||||
return year + "-" + month + "-" + day;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前时间
|
||||
* @return
|
||||
*/
|
||||
public static String getCurTimeStr() {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
String year = String.valueOf(g.get(Calendar.YEAR));
|
||||
String month = String.format("%02d", g.get(Calendar.MONTH) + 1);
|
||||
String day = String.format("%02d", g.get(Calendar.DAY_OF_MONTH));
|
||||
String hours = String.format("%02d", g.get(Calendar.HOUR_OF_DAY));
|
||||
String minutes = String.format("%02d", g.get(Calendar.MINUTE));
|
||||
String seconds = String.format("%02d", g.get(Calendar.SECOND));
|
||||
|
||||
return year + month + day + hours + minutes + seconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化时间
|
||||
* @param time
|
||||
* @param oldFormat
|
||||
* @param newFormat
|
||||
* @return
|
||||
*/
|
||||
public static String formatTime(String time, String oldFormat,
|
||||
String newFormat) {
|
||||
return new SimpleDateFormat(newFormat).format(stringToDate(time,
|
||||
oldFormat));
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化日期
|
||||
* @param date
|
||||
* @param format
|
||||
* @return
|
||||
*/
|
||||
public static String formatTime(Date date, String format) {
|
||||
return new SimpleDateFormat(format).format(date);
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化时间
|
||||
* @param time
|
||||
* @param format
|
||||
* @return
|
||||
*/
|
||||
public static String formatTime(long time, String format) {
|
||||
return formatTime(getTime(time), "yyyy-MM-dd HH:mm:ss", format);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取时间, 根据格式化参数
|
||||
* @param time
|
||||
* @param format
|
||||
* @return
|
||||
*/
|
||||
public static long formatTime(String time, String format) {
|
||||
return stringToDate(time, format).getTime();
|
||||
}
|
||||
|
||||
public static String dateForm(String date, String config) {
|
||||
if ("MM/dd/yyyy".equals(config)) {
|
||||
String[] dateStrs = date.split("/");
|
||||
return dateStrs[2] + "-" + dateStrs[0] + "-" + dateStrs[1];
|
||||
}
|
||||
if ("MM-dd-yyyy".equals(config)) {
|
||||
String[] dateStrs = date.split("-");
|
||||
return dateStrs[2] + "-" + dateStrs[0] + "-" + dateStrs[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static int getYear(String time) {
|
||||
return Integer.parseInt(time.substring(0, 4));
|
||||
}
|
||||
|
||||
public static int getMonth(String time) {
|
||||
return Integer.parseInt(time.substring(5, 7));
|
||||
}
|
||||
|
||||
public static int getDay(String time) {
|
||||
return Integer.parseInt(time.substring(8, 10));
|
||||
}
|
||||
|
||||
public static int getHours(String time) {
|
||||
return Integer.parseInt(time.substring(11, 13));
|
||||
}
|
||||
|
||||
public static int getMinutes(String time) {
|
||||
return Integer.parseInt(time.substring(14, 16));
|
||||
}
|
||||
|
||||
public static int getSeconds(String time) {
|
||||
return Integer.parseInt(time.substring(17));
|
||||
}
|
||||
|
||||
public static int getYear() {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
return g.get(Calendar.YEAR);
|
||||
}
|
||||
|
||||
public static int getMonth() {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
return g.get(Calendar.MONTH) + 1;
|
||||
}
|
||||
|
||||
public static int getDay() {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
return g.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
|
||||
public static int getHours() {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
return g.get(Calendar.HOUR_OF_DAY);
|
||||
}
|
||||
|
||||
public static int getMinutes() {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
return g.get(Calendar.MINUTE);
|
||||
}
|
||||
|
||||
public static int getSeconds() {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
return g.get(Calendar.SECOND);
|
||||
}
|
||||
|
||||
public static String getBeforeTimeByMinute(int minute) {
|
||||
GregorianCalendar g = new GregorianCalendar();
|
||||
g.set(Calendar.MINUTE, g.get(Calendar.MINUTE) - minute);
|
||||
return dateToString(g);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,846 @@
|
||||
package javautils.date;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
public class Moment {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Moment moment = new Moment();
|
||||
System.out.println(moment.difference(new Moment().fromDate("2015-01-18"), "hour"));
|
||||
}
|
||||
|
||||
static {
|
||||
TimeZone china = TimeZone.getTimeZone("Asia/Shanghai");
|
||||
TimeZone.setDefault(china);
|
||||
}
|
||||
|
||||
public GregorianCalendar gc;
|
||||
|
||||
public Moment() {
|
||||
gc = new GregorianCalendar();
|
||||
gc.setFirstDayOfWeek(Calendar.MONDAY);
|
||||
}
|
||||
|
||||
public Moment(GregorianCalendar gc) {
|
||||
this.gc = gc;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据日期获取对象
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public Moment fromDate(String date) {
|
||||
try {
|
||||
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
|
||||
Date d = format.parse(date);
|
||||
gc.setTime(d);
|
||||
} catch (Exception e) {}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从日期转换
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public Moment fromDate(Date date) {
|
||||
gc.setTime(date);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据时间获取对象
|
||||
* @param time
|
||||
* @return
|
||||
*/
|
||||
public Moment fromTime(String time) {
|
||||
try {
|
||||
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
Date d = format.parse(time);
|
||||
gc.setTime(d);
|
||||
} catch (Exception e) {}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据时间+format
|
||||
* @param time
|
||||
* @param formatStr
|
||||
* @return
|
||||
*/
|
||||
public Moment fromTime(String time, String formatStr) {
|
||||
try {
|
||||
DateFormat format = new SimpleDateFormat(formatStr);
|
||||
Date d = format.parse(time);
|
||||
gc.setTime(d);
|
||||
} catch (Exception e) {}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换成普通时间 1900-01-01 12:00:00
|
||||
* @return
|
||||
*/
|
||||
public String toSimpleTime() {
|
||||
return year() + "-" + months() + "-" + days() + " " + hours() + ":" + minutes() + ":" + seconds();
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换成完整时间1900-01-01 12:00:00.000
|
||||
* @return
|
||||
*/
|
||||
public String toFullTime() {
|
||||
return toSimpleTime() + "." + milliseconds();
|
||||
}
|
||||
|
||||
/**
|
||||
* 转成日期格式1900-01-01
|
||||
* @return
|
||||
*/
|
||||
public String toSimpleDate() {
|
||||
return year() + "-" + months() + "-" + days();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取date对象
|
||||
* @return
|
||||
*/
|
||||
public Date toDate() {
|
||||
return gc.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据参数格式化
|
||||
* y年
|
||||
* M月
|
||||
* d日
|
||||
* H时
|
||||
* m分
|
||||
* s秒
|
||||
* @param format
|
||||
* @return
|
||||
*/
|
||||
public String format(String format) {
|
||||
return new SimpleDateFormat(format).format(toDate());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取年份
|
||||
*
|
||||
* @return
|
||||
* @return
|
||||
*/
|
||||
public int year() {
|
||||
return gc.get(Calendar.YEAR);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置年份
|
||||
*
|
||||
* @param year
|
||||
*/
|
||||
public Moment year(int year) {
|
||||
gc.set(Calendar.YEAR, year);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取月份
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int month() {
|
||||
return gc.get(Calendar.MONTH) + 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取完整月份
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String months() {
|
||||
return String.format("%02d", month());
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置月份
|
||||
*
|
||||
* @param month
|
||||
* @return
|
||||
*/
|
||||
public Moment month(int month) {
|
||||
if (month > 0 && month <= 12) {
|
||||
gc.set(Calendar.MONTH, month - 1);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置月份
|
||||
*
|
||||
* @param month
|
||||
* @return
|
||||
*/
|
||||
public Moment month(String month) {
|
||||
month(Integer.parseInt(month));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取天
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int day() {
|
||||
return gc.get(Calendar.DAY_OF_MONTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取完整天
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String days() {
|
||||
return String.format("%02d", day());
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置天
|
||||
*
|
||||
* @param day
|
||||
* @return
|
||||
*/
|
||||
public Moment day(int day) {
|
||||
if (day > 0 && day <= 31) {
|
||||
gc.set(Calendar.DAY_OF_MONTH, day);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置天
|
||||
*
|
||||
* @param day
|
||||
* @return
|
||||
*/
|
||||
public Moment day(String day) {
|
||||
day(Integer.parseInt(day));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取小时
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int hour() {
|
||||
return gc.get(Calendar.HOUR_OF_DAY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取小时
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String hours() {
|
||||
return String.format("%02d", hour());
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置小时
|
||||
*
|
||||
* @param hour
|
||||
* @return
|
||||
*/
|
||||
public Moment hour(int hour) {
|
||||
if (hour >= 0 && hour < 24) {
|
||||
gc.set(Calendar.HOUR_OF_DAY, hour);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置小时
|
||||
*
|
||||
* @param hour
|
||||
* @return
|
||||
*/
|
||||
public Moment hour(String hour) {
|
||||
hour(Integer.parseInt(hour));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取分钟
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int minute() {
|
||||
return gc.get(Calendar.MINUTE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取分钟
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String minutes() {
|
||||
return String.format("%02d", minute());
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置分钟
|
||||
*
|
||||
* @param minute
|
||||
* @return
|
||||
*/
|
||||
public Moment minute(int minute) {
|
||||
if (minute >= 0 && minute < 60) {
|
||||
gc.set(Calendar.MINUTE, minute);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置分钟
|
||||
*
|
||||
* @param minute
|
||||
* @return
|
||||
*/
|
||||
public Moment minute(String minute) {
|
||||
minute(Integer.parseInt(minute));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取秒
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int second() {
|
||||
return gc.get(Calendar.SECOND);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取秒
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String seconds() {
|
||||
return String.format("%02d", second());
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置秒
|
||||
*
|
||||
* @param second
|
||||
* @return
|
||||
*/
|
||||
public Moment second(int second) {
|
||||
if (second >= 0 && second < 60) {
|
||||
gc.set(Calendar.SECOND, second);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置秒
|
||||
*
|
||||
* @param second
|
||||
* @return
|
||||
*/
|
||||
public Moment second(String second) {
|
||||
second(Integer.parseInt(second));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取毫秒
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int millisecond() {
|
||||
return gc.get(Calendar.MILLISECOND);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取毫秒
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public String milliseconds() {
|
||||
return String.format("%03d", millisecond());
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置毫秒
|
||||
*
|
||||
* @param millisecond
|
||||
* @return
|
||||
*/
|
||||
public Moment millisecond(int millisecond) {
|
||||
if (millisecond >= 0 && millisecond < 1000) {
|
||||
gc.set(Calendar.MILLISECOND, millisecond);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置毫秒
|
||||
*
|
||||
* @param millisecond
|
||||
* @return
|
||||
*/
|
||||
public Moment millisecond(String millisecond) {
|
||||
millisecond(Integer.parseInt(millisecond));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前日期在本月的第几周
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int weekOfMonth() {
|
||||
return gc.get(Calendar.WEEK_OF_MONTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前日期在本年的第几周
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int weekOfYear() {
|
||||
return gc.get(Calendar.WEEK_OF_YEAR);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取星期几
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int dayOfWeek() {
|
||||
int field = gc.get(Calendar.DAY_OF_WEEK);
|
||||
switch (field) {
|
||||
case Calendar.SUNDAY:
|
||||
return 7;
|
||||
case Calendar.MONDAY:
|
||||
return 1;
|
||||
case Calendar.TUESDAY:
|
||||
return 2;
|
||||
case Calendar.WEDNESDAY:
|
||||
return 3;
|
||||
case Calendar.THURSDAY:
|
||||
return 4;
|
||||
case Calendar.FRIDAY:
|
||||
return 5;
|
||||
case Calendar.SATURDAY:
|
||||
return 6;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return gc.getFirstDayOfWeek();
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置星期几
|
||||
* @param week
|
||||
* @return
|
||||
*/
|
||||
public Moment dayOfWeek(int week) {
|
||||
switch (week) {
|
||||
case 7:
|
||||
gc.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
|
||||
break;
|
||||
case 1:
|
||||
gc.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
|
||||
break;
|
||||
case 2:
|
||||
gc.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
|
||||
break;
|
||||
case 3:
|
||||
gc.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
|
||||
break;
|
||||
case 4:
|
||||
gc.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
|
||||
break;
|
||||
case 5:
|
||||
gc.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
|
||||
break;
|
||||
case 6:
|
||||
gc.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前日期在本年的第几天
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int dayOfYear() {
|
||||
return gc.get(Calendar.DAY_OF_YEAR);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置日期为本年的第几天
|
||||
*
|
||||
* @param day
|
||||
* @return
|
||||
*/
|
||||
public Moment dayOfYear(int day) {
|
||||
gc.set(Calendar.DAY_OF_YEAR, day);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前日期所在季度 1月~3月 第一季度 4月~6月 第二季度 7月~9月 第三季度 10月~12月 第四季度
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public int quarter() {
|
||||
int month = month();
|
||||
switch (month) {
|
||||
case 1:
|
||||
case 2:
|
||||
case 3:
|
||||
return 1;
|
||||
case 4:
|
||||
case 5:
|
||||
case 6:
|
||||
return 2;
|
||||
case 7:
|
||||
case 8:
|
||||
case 9:
|
||||
return 3;
|
||||
case 10:
|
||||
case 11:
|
||||
case 12:
|
||||
return 4;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据参数获取
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public int get(String key) {
|
||||
switch (key) {
|
||||
case "year":
|
||||
return year();
|
||||
case "month":
|
||||
return month();
|
||||
case "day":
|
||||
case "date":
|
||||
return day();
|
||||
case "hour":
|
||||
return hour();
|
||||
case "minute":
|
||||
return minute();
|
||||
case "second":
|
||||
return second();
|
||||
case "millisecond":
|
||||
return millisecond();
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据参数设置值
|
||||
*
|
||||
* @param key
|
||||
* @param value
|
||||
* @return
|
||||
*/
|
||||
public Moment set(String key, int value) {
|
||||
switch (key) {
|
||||
case "year":
|
||||
year(value);
|
||||
break;
|
||||
case "month":
|
||||
month(value);
|
||||
break;
|
||||
case "day":
|
||||
case "date":
|
||||
day(value);
|
||||
break;
|
||||
case "hour":
|
||||
hour(value);
|
||||
break;
|
||||
case "minute":
|
||||
minute(value);
|
||||
break;
|
||||
case "second":
|
||||
second(value);
|
||||
break;
|
||||
case "millisecond":
|
||||
millisecond(value);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取millis时间
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public long millis() {
|
||||
return gc.getTimeInMillis();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取其中时间最大的那个
|
||||
*
|
||||
* @param moment
|
||||
* @return
|
||||
*/
|
||||
public static Moment max(final Moment... moment) {
|
||||
Moment max = null;
|
||||
if (moment != null && moment.length > 0) {
|
||||
for (Moment tmp : moment) {
|
||||
if (max == null) {
|
||||
max = tmp;
|
||||
}
|
||||
if (max.millis() < tmp.millis()) {
|
||||
max = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取其中时间最小的那个
|
||||
*
|
||||
* @param moment
|
||||
* @return
|
||||
*/
|
||||
public static Moment min(final Moment... moment) {
|
||||
Moment min = null;
|
||||
if (moment != null && moment.length > 0) {
|
||||
for (Moment tmp : moment) {
|
||||
if (min == null) {
|
||||
min = tmp;
|
||||
}
|
||||
if (min.millis() > tmp.millis()) {
|
||||
min = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加指定key的时间
|
||||
* @param number
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public Moment add(int amount, String key) {
|
||||
switch (key) {
|
||||
case "years":
|
||||
case "y":
|
||||
gc.add(Calendar.YEAR, amount);
|
||||
break;
|
||||
case "quarters":
|
||||
case "Q":
|
||||
gc.add(Calendar.MONTH, amount * 3);
|
||||
break;
|
||||
case "months":
|
||||
case "M":
|
||||
gc.add(Calendar.MONTH, amount);
|
||||
break;
|
||||
case "weeks":
|
||||
case "w":
|
||||
gc.add(Calendar.WEEK_OF_YEAR, amount);
|
||||
break;
|
||||
case "days":
|
||||
case "d":
|
||||
gc.add(Calendar.DAY_OF_MONTH, amount);
|
||||
break;
|
||||
case "hours":
|
||||
case "h":
|
||||
gc.add(Calendar.HOUR_OF_DAY, amount);
|
||||
break;
|
||||
case "minutes":
|
||||
case "m":
|
||||
gc.add(Calendar.MINUTE, amount);
|
||||
break;
|
||||
case "seconds":
|
||||
case "s":
|
||||
gc.add(Calendar.SECOND, amount);
|
||||
break;
|
||||
case "milliseconds":
|
||||
case "ms":
|
||||
gc.add(Calendar.MILLISECOND, amount);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 减去指定key的时间
|
||||
* @param number
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public Moment subtract(int amount, String key) {
|
||||
return add(-amount, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取key的开始时间
|
||||
*
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public Moment startOf(String key) {
|
||||
Moment moment = new Moment( (GregorianCalendar) this.gc.clone());
|
||||
switch (key) {
|
||||
case "year":
|
||||
moment.dayOfYear(1).hour(0).minute(0).second(0).millisecond(0);
|
||||
break;
|
||||
case "month":
|
||||
moment.day(1).hour(0).minute(0).second(0).millisecond(0);
|
||||
break;
|
||||
case "week":
|
||||
moment.dayOfWeek(1).hour(0).minute(0).second(0).millisecond(0);
|
||||
break;
|
||||
case "day":
|
||||
moment.hour(0).minute(0).second(0).millisecond(0);
|
||||
break;
|
||||
case "hour":
|
||||
moment.minute(0).second(0).millisecond(0);
|
||||
case "minute":
|
||||
moment.second(0).millisecond(0);
|
||||
break;
|
||||
case "second":
|
||||
moment.millisecond(0);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return moment;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取key的结束时间
|
||||
*
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public Moment endOf(String key) {
|
||||
Moment moment = new Moment();
|
||||
switch (key) {
|
||||
case "year":
|
||||
return moment.startOf(key).add(1, "years").subtract(1, "days").hour(23).minute(59).second(59).millisecond(999);
|
||||
case "month":
|
||||
return moment.startOf(key).add(1, "months").subtract(1, "days").hour(23).minute(59).second(59).millisecond(999);
|
||||
case "week":
|
||||
return moment.startOf(key).add(1, "weeks").subtract(1, "days").hour(23).minute(59).second(59).millisecond(999);
|
||||
case "day":
|
||||
return moment.startOf(key).hour(23).minute(59).second(59).millisecond(999);
|
||||
case "hour":
|
||||
return moment.startOf(key).minute(59).second(59).millisecond(999);
|
||||
case "minute":
|
||||
return moment.startOf(key).second(59).millisecond(999);
|
||||
case "second":
|
||||
return moment.startOf(key).millisecond(999);
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return moment;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取时间差值
|
||||
* @param moment
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public int difference(Moment moment, String key) {
|
||||
switch (key) {
|
||||
case "year":
|
||||
return this.year() - moment.year();
|
||||
case "month":
|
||||
return difference(moment, "year") * 12 + (this.month() - moment.month());
|
||||
case "day":
|
||||
return (int) ((this.millis() - moment.millis()) / (24 * 60 * 60 * 1000));
|
||||
case "hour":
|
||||
return (int) ((this.millis() - moment.millis()) / (60 * 60 * 1000));
|
||||
case "minute":
|
||||
return (int) ((this.millis() - moment.millis()) / (60 * 1000));
|
||||
case "second":
|
||||
return (int) ((this.millis() - moment.millis()) / (1000));
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 大于另一个日期
|
||||
* @param moment
|
||||
* @return
|
||||
*/
|
||||
public boolean gt(Moment moment) {
|
||||
return (this.millis() > moment.millis()) ? true : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 小于另一个日期
|
||||
* @param moment
|
||||
* @return
|
||||
*/
|
||||
public boolean lt(Moment moment) {
|
||||
return (this.millis() < moment.millis()) ? true : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 大于或者等于另一个日期
|
||||
* @param moment
|
||||
* @return
|
||||
*/
|
||||
public boolean ge(Moment moment) {
|
||||
return (this.millis() >= moment.millis()) ? true : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 小于或者等于另一个日期
|
||||
* @param moment
|
||||
* @return
|
||||
*/
|
||||
public boolean le(Moment moment) {
|
||||
return (this.millis() <= moment.millis()) ? true : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在两个日期之间
|
||||
* @param sMoment
|
||||
* @param eMoment
|
||||
* @return
|
||||
*/
|
||||
public boolean between(Moment sMoment, Moment eMoment) {
|
||||
return (this.ge(sMoment) && this.le(eMoment)) ? true : false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package javautils.deal;
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.UUID;
|
||||
|
||||
public class OrderUtil {
|
||||
|
||||
/**
|
||||
* 获取随机字符串
|
||||
* @param length
|
||||
* @param isNumber
|
||||
* @return
|
||||
*/
|
||||
public static String getBillno(int length, boolean isNumber) {
|
||||
String uuid = UUID.randomUUID().toString().replace("-", "");
|
||||
if(isNumber) {
|
||||
uuid = uuid.replace("a", "1").replace("b", "2").replace("c", "3").replace("d", "4").replace("e", "5").replace("f", "6");
|
||||
}
|
||||
if(uuid.length() < length) {
|
||||
uuid += getBillno(length - uuid.length(), isNumber);
|
||||
} else {
|
||||
uuid = uuid.substring(0, length);
|
||||
}
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建随机字符串
|
||||
* @param config
|
||||
* @return
|
||||
*/
|
||||
public static String createString(int length) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
char ch[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1'};
|
||||
Random random = new Random();
|
||||
if (length > 0) {
|
||||
int index = 0;
|
||||
char[] temp = new char[length];
|
||||
int num = random.nextInt();
|
||||
for (int i = 0; i < length % 5; i++) {
|
||||
temp[index++] = ch[num & 63];
|
||||
num >>= 6;
|
||||
}
|
||||
for (int i = 0; i < length / 5; i++) {
|
||||
num = random.nextInt();
|
||||
for (int j = 0; j < 5; j++) {
|
||||
temp[index++] = ch[num & 63];
|
||||
num >>= 6;
|
||||
}
|
||||
}
|
||||
sb.append(new String(temp, 0, length));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建随机字符串
|
||||
* Example like {6, "-", 9}
|
||||
* @param config
|
||||
* @return
|
||||
*/
|
||||
public static String createString(Object[] config) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (Object key : config) {
|
||||
if(key instanceof Integer) {
|
||||
sb.append(createString((Integer)key));
|
||||
}
|
||||
if(key instanceof String) {
|
||||
sb.append(key);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package javautils.email;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
|
||||
import javax.mail.internet.MimeMessage;
|
||||
import java.util.Properties;
|
||||
|
||||
public class SpringMailUtil {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SpringMailUtil.class);
|
||||
|
||||
private String username;
|
||||
private String personal;
|
||||
private String password;
|
||||
private String host;
|
||||
private String defaultEncoding = "UTF-8";
|
||||
|
||||
public SpringMailUtil(String username, String personal, String password, String host) {
|
||||
this.username = username;
|
||||
this.personal = personal;
|
||||
this.password = password;
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
public boolean send(String to, String subject, String htmlText) {
|
||||
return sendInternal(to, subject, htmlText);
|
||||
}
|
||||
|
||||
public boolean sendInternal(String to, String subject, String htmlText) {
|
||||
try {
|
||||
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
|
||||
mailSender.setDefaultEncoding(defaultEncoding);
|
||||
mailSender.setHost(host);
|
||||
mailSender.setUsername(username);
|
||||
mailSender.setPassword(password);
|
||||
Properties properties = new Properties();
|
||||
properties.put("mail.smtp.auth", "true");
|
||||
properties.put("mail.smtp.starttls.enable", "true");
|
||||
properties.put("mail.smtp.host", host);
|
||||
properties.put("mail.smtp.user", username);
|
||||
properties.put("mail.smtp.password", password);
|
||||
properties.put("mail.smtp.port", "587");
|
||||
properties.put("mail.smtp.auth", "true");
|
||||
mailSender.setJavaMailProperties(properties);
|
||||
|
||||
MimeMessage mimeMessage = mailSender.createMimeMessage();
|
||||
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
|
||||
messageHelper.setTo(to);
|
||||
messageHelper.setFrom(username, personal);
|
||||
messageHelper.setSubject(subject);
|
||||
messageHelper.setText(htmlText, true);
|
||||
mailSender.send(mimeMessage);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
logger.error("发送邮件失败!", e == null ? "" : e.getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package javautils.encrypt;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.security.Key;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
|
||||
public class AESUtil {
|
||||
|
||||
/*
|
||||
* 算法/模式/填充 16字节加密后数据长度 不满16字节加密后长度
|
||||
* AES/CBC/NoPadding 16 不支持
|
||||
* AES/CBC/PKCS5Padding 32 16
|
||||
* AES/CBC/ISO10126Padding 32 16
|
||||
* AES/CFB/NoPadding 16 原始数据长度
|
||||
* AES/CFB/PKCS5Padding 32 16
|
||||
* AES/CFB/ISO10126Padding 32 16
|
||||
* AES/ECB/NoPadding 16 不支持
|
||||
* AES/ECB/PKCS5Padding 32 16
|
||||
* AES/ECB/ISO10126Padding 32 16
|
||||
* AES/OFB/NoPadding 16 原始数据长度
|
||||
* AES/OFB/PKCS5Padding 32 16
|
||||
* AES/OFB/ISO10126Padding 32 16
|
||||
* AES/PCBC/NoPadding 16 不支持
|
||||
* AES/PCBC/PKCS5Padding 32 16
|
||||
* AES/PCBC/ISO10126Padding 32 16
|
||||
*
|
||||
* 注:
|
||||
* 1、JCE中AES支持五中模式:CBC,CFB,ECB,OFB,PCBC;支持三种填充:NoPadding,PKCS5Padding,ISO10126Padding。 不带模式和填充来获取AES算法的时候,其默认使用ECB/PKCS5Padding。
|
||||
* 2、Java支持的密钥长度:keysize must be equal to 128, 192 or 256
|
||||
* 3、Java默认限制使用大于128的密钥加密(解密不受限制),报错信息:java.security.InvalidKeyException: Illegal key size or default parameters
|
||||
* 4、下载并安装JCE Policy文件即可突破128密钥长度的限制:覆盖jre\lib\security目录下local_policy.jar、US_export_policy.jar文件即可
|
||||
* 5、除ECB外,需提供初始向量(IV),如:Cipher.init(opmode, key, new IvParameterSpec(iv)), 且IV length: must be 16 bytes long
|
||||
*/
|
||||
|
||||
public static final String ALGORITHM = "AES";
|
||||
public static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
|
||||
|
||||
/**
|
||||
* 生成随机密钥
|
||||
*
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Key generateKey(int keysize) throws Exception {
|
||||
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
|
||||
keyGenerator.init(keysize, new SecureRandom());
|
||||
Key key = keyGenerator.generateKey();
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机密钥
|
||||
*
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Key generateKey() throws Exception {
|
||||
return generateKey(128);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成固定密钥
|
||||
*
|
||||
* @param password 作为种子,生成对应的密钥
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Key generateKey(int keysize, byte[] seed) throws Exception {
|
||||
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
|
||||
keyGenerator.init(keysize, new SecureRandom(seed));
|
||||
Key key = keyGenerator.generateKey();
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成固定密钥
|
||||
*
|
||||
* @param password 作为种子,生成对应的密钥
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Key generateKey(int keysize, String password) throws Exception {
|
||||
return generateKey(keysize, password.getBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成固定密钥
|
||||
*
|
||||
* @param password 作为种子,生成对应的密钥
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Key generateKey(String password) throws Exception {
|
||||
return generateKey(128, password);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行加密
|
||||
*
|
||||
* @param content
|
||||
* @param key 长度必须为16、24、32位,即128bit、192bit、256bit
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static byte[] encrypt(byte[] content, byte[] key) throws Exception {
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, ALGORITHM));
|
||||
byte[] output = cipher.doFinal(content);
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行加密
|
||||
*
|
||||
* @param content
|
||||
* @param password 作为种子,生成对应的密钥
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static byte[] encrypt(byte[] content, String password) throws Exception {
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, generateKey(password));
|
||||
byte[] output = cipher.doFinal(content);
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行解密
|
||||
*
|
||||
* @param content
|
||||
* @param key 长度必须为16、24、32位,即128bit、192bit、256bit
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static byte[] decrypt(byte[] content, byte[] key) throws Exception {
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, ALGORITHM));
|
||||
byte[] output = cipher.doFinal(content);
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行解密
|
||||
*
|
||||
* @param content
|
||||
* @param password
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static byte[] decrypt(byte[] content, String password) throws Exception {
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.DECRYPT_MODE, generateKey(password));
|
||||
byte[] output = cipher.doFinal(content);
|
||||
return output;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
System.out.println(Arrays.toString(encrypt("当我们把密钥定为大于128时(即192或256)时".getBytes(), "012345")));
|
||||
System.out.println(new String(decrypt(encrypt("当我们把密钥定为大于128时(即192或256)时".getBytes(), "012345"), "012345")));
|
||||
|
||||
System.out.println(Arrays.toString(encrypt("当我们把密钥定为大于128时(即192或256)时".getBytes(), "01234567890123450123456789012345".getBytes())));
|
||||
System.out.println(new String(decrypt(encrypt("当我们把密钥定为大于128时(即192或256)时".getBytes(), "01234567890123450123456789012345".getBytes()), "01234567890123450123456789012345".getBytes())));
|
||||
|
||||
/*
|
||||
* 控制台输出:
|
||||
*
|
||||
* [-75, 23, -15, -7, -91, 91, -105, 15, 69, -10, -69, 15, 78, 67, -86, -55, 92, 43, -47, -112, -2, 7, -128, -49, -104, -6, 35, -25, -47, -124, -38, -39, 51, -8, -37, 32, 21, -44, -88, -61, -51, -15, -31, 100, 87, -50, -81, -43, -71, 38, -59, -67, -92, 15, 125, 39, -34, 120, -113, -14, -35, -94, -86, 40]
|
||||
* 当我们把密钥定为大于128时(即192或256)时
|
||||
* [-67, 65, -65, -13, -5, 106, -127, -37, 87, 114, 99, 10, -52, -106, 48, -76, 96, 108, -92, 91, 28, 117, -37, -14, 55, -24, -80, 86, 54, 0, -82, -62, 31, 127, -101, 36, -10, 35, -60, -52, 127, -60, -27, -107, 56, 64, -127, -64, 112, -116, -28, -30, 61, -121, 75, -16, -40, -26, -96, -99, -85, 48, 63, -13]
|
||||
* 当我们把密钥定为大于128时(即192或256)时
|
||||
*/
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package javautils.encrypt;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
|
||||
/**
|
||||
* Created by Nick on 2017-07-01.
|
||||
*/
|
||||
public class Base64Util {
|
||||
// 加密
|
||||
public static String getBase64(String str) {
|
||||
byte[] b = null;
|
||||
String s = null;
|
||||
try {
|
||||
b = str.getBytes("utf-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (b != null) {
|
||||
s = new Base64().encodeBase64String(b);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// 解密
|
||||
public static String getFromBase64(String s) {
|
||||
byte[] b = null;
|
||||
String result = null;
|
||||
if (s != null) {
|
||||
Base64 decoder = new Base64();
|
||||
try {
|
||||
b = decoder.decodeBase64(s);
|
||||
result = new String(b, "utf-8");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package javautils.encrypt;
|
||||
|
||||
import java.security.Key;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.DESKeySpec;
|
||||
|
||||
import javautils.http.UrlParamUtils;
|
||||
import lottery.domains.pool.payment.pay41.utils.URLUtils;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.http.client.utils.URLEncodedUtils;
|
||||
import org.springframework.util.Base64Utils;
|
||||
|
||||
/**
|
||||
* DES加密工具类
|
||||
*/
|
||||
public class DESUtil {
|
||||
|
||||
private DESUtil() {
|
||||
|
||||
}
|
||||
|
||||
public static DESUtil getInstance() {
|
||||
return new DESUtil();
|
||||
}
|
||||
|
||||
private Key getKey(String strKey) {
|
||||
try {
|
||||
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
|
||||
DESKeySpec keySpec = new DESKeySpec(strKey.getBytes());
|
||||
keyFactory.generateSecret(keySpec);
|
||||
return keyFactory.generateSecret(keySpec);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String encryptStr(String strMing, String keyStr) {
|
||||
try {
|
||||
byte[] byteMing = strMing.getBytes();
|
||||
byte[] byteMi = encryptByte(byteMing, getKey(keyStr));
|
||||
return new String(Base64.encodeBase64(byteMi));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public String decryptStr(String strMi, String keyStr) {
|
||||
try {
|
||||
byte[] byteMi = Base64.decodeBase64(strMi.getBytes());
|
||||
byte[] byteMing = decryptByte(byteMi, getKey(keyStr));
|
||||
String strMing = new String(byteMing);
|
||||
return strMing;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private byte[] encryptByte(byte[] byteS, Key key) {
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("DES");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key);
|
||||
return cipher.doFinal(byteS);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private byte[] decryptByte(byte[] byteD, Key key) {
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("DES");
|
||||
cipher.init(Cipher.DECRYPT_MODE, key);
|
||||
return cipher.doFinal(byteD);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
String str = "d0d2908159af41c9a2464e2c1816ea07";
|
||||
String key = "asd$65699))*i-23";
|
||||
|
||||
|
||||
String encrypt = DESUtil.getInstance().encryptStr(str, key);
|
||||
System.out.println(encrypt);
|
||||
encrypt = URLEncodeUtil.encode(encrypt, "UTF-8");
|
||||
System.out.println(encrypt);
|
||||
|
||||
encrypt = URLEncodeUtil.decode(encrypt, "UTF-8");
|
||||
|
||||
System.out.println(encrypt);
|
||||
|
||||
String decrypt = DESUtil.getInstance().decryptStr(encrypt, key);
|
||||
System.out.println(decrypt);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package javautils.encrypt;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
/**
|
||||
* 该工具类与前端md5.js一致
|
||||
* Created by Nick on 2017-06-28.
|
||||
*/
|
||||
public class MD5Util {
|
||||
private static final String KEY_MD5 = "MD5";
|
||||
// 全局数组
|
||||
private static final String[] strDigits = { "0", "1", "2", "3", "4", "5",
|
||||
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
|
||||
|
||||
// 返回形式为数字跟字符串
|
||||
private static String byteToArrayString(byte bByte) {
|
||||
int iRet = bByte;
|
||||
if (iRet < 0) {
|
||||
iRet += 256;
|
||||
}
|
||||
int iD1 = iRet / 16;
|
||||
int iD2 = iRet % 16;
|
||||
return strDigits[iD1] + strDigits[iD2];
|
||||
}
|
||||
|
||||
// 转换字节数组为16进制字串
|
||||
private static String byteToString(byte[] bByte) {
|
||||
StringBuffer sBuffer = new StringBuffer();
|
||||
for (int i = 0; i < bByte.length; i++) {
|
||||
sBuffer.append(byteToArrayString(bByte[i]));
|
||||
}
|
||||
return sBuffer.toString();
|
||||
}
|
||||
/**
|
||||
* MD5加密
|
||||
* @param strObj
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String getMD5Code(String strObj){
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance(KEY_MD5);
|
||||
// md.digest() 该函数返回值为存放哈希值结果的byte数组
|
||||
return byteToString(md.digest(strObj.getBytes()));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package javautils.encrypt;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
import java.util.HashSet;
|
||||
|
||||
public class PasswordUtil {
|
||||
private static HashSet<String> SIMPLE_PASSWORS = new HashSet<>();
|
||||
|
||||
private final static String[] SIMPLE_DIGITS = { "A", "B", "C", "D", "E", "F",
|
||||
"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f",
|
||||
"g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
|
||||
static {
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString("12"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString("123"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString("1234"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString("12345"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString("123456"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString("1234567"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString("12345678"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString("123456789"));
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(i+"", 6)));
|
||||
}
|
||||
|
||||
// 简单密码
|
||||
for (String simpleDigit : SIMPLE_DIGITS) {
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 6)));
|
||||
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(simpleDigit + "12345"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(simpleDigit + "123456"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(simpleDigit + "1234567"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(simpleDigit + "12345678"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(simpleDigit + "123456789"));
|
||||
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 2) + "1234"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 2) + "12345"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 2) + "123456"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 2) + "1234567"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 2) + "12345678"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 2) + "123456789"));
|
||||
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 3) + "123"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 3) + "1234"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 3) + "12345"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 3) + "123456"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 3) + "1234567"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 3) + "12345678"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 3) + "123456789"));
|
||||
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 4) + "12"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 4) + "123"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 4) + "1234"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 4) + "12345"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 4) + "123456"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 4) + "1234567"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 4) + "12345678"));
|
||||
SIMPLE_PASSWORS.add(generatePasswordByPlainString(StringUtils.repeat(simpleDigit, 4) + "123456789"));
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isSimplePassword(String md5Pwd) {
|
||||
return SIMPLE_PASSWORS.contains(md5Pwd);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把给定的MD5字符串加密成密码
|
||||
* @param md5String 密码前台传输时的加密方式:MD5大写(MD5大写(密码明文),调用$.generatePassword(plainStr)即可
|
||||
* @return
|
||||
*/
|
||||
public static String generatePasswordByMD5(String md5String) {
|
||||
return MD5Util.getMD5Code(md5String).toUpperCase();
|
||||
}
|
||||
/**
|
||||
* 把明文字符串加密成数据库密码,直接存入数据库即可
|
||||
* @param plainString 明文字符串
|
||||
* @return
|
||||
*/
|
||||
public static String generatePasswordByPlainString(String plainString) {
|
||||
String password = MD5Util.getMD5Code(plainString).toUpperCase(); // 第一次加密,并转换成大写
|
||||
|
||||
password = MD5Util.getMD5Code(password).toUpperCase(); // 第二次加密,并转换成大写
|
||||
|
||||
password = MD5Util.getMD5Code(password).toUpperCase(); // 第三次加密,并转换成大写
|
||||
|
||||
return password;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 验证输入的密码是否正确
|
||||
* @param dbPassword
|
||||
* 数据库密码
|
||||
* @param token
|
||||
* 加密token
|
||||
* @param md5String
|
||||
* 密码前台传输时的加密方式:MD5大写(MD5大写(MD5大写(MD5大写(密码明文))) + token),调用$.encryptPasswordWithToken(plainStr, token)
|
||||
* @return 验证结果,TRUE:正确 FALSE:错误
|
||||
*/
|
||||
public static boolean validatePassword(String dbPassword, String token, String md5String) {
|
||||
String dbPasswordWithToken = MD5Util.getMD5Code(dbPassword + token).toUpperCase();
|
||||
|
||||
return md5String.equals(dbPasswordWithToken);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证是否是一样的密码
|
||||
* @param dbPassword 数据库密码
|
||||
* @param md5String 密码前台传输时的加密方式:MD5大写(MD5大写(密码明文),调用$.encryptPasswordWithToken(plainStr, token)
|
||||
* @return
|
||||
*/
|
||||
public static boolean validateSamePassword(String dbPassword, String md5String) {
|
||||
String inputPassword = generatePasswordByMD5(md5String);
|
||||
|
||||
return dbPassword.equals(inputPassword);
|
||||
}
|
||||
|
||||
//生成密码
|
||||
public static void main(String[] args) {
|
||||
String password = "123456";
|
||||
password = generatePasswordByPlainString(password);
|
||||
System.out.println(password);
|
||||
|
||||
password = "123456";
|
||||
password = generatePasswordByPlainString(password);
|
||||
System.out.println(password);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package javautils.encrypt;
|
||||
|
||||
public class PaymentChannelEncrypt {
|
||||
public static void main(String[] args) {
|
||||
String encrypt = encrypt("http:127.0.0.1:12");
|
||||
String decrypt = decrypt(encrypt);
|
||||
System.out.println(encrypt);
|
||||
System.out.println(decrypt("cQ154u+Dtqqw6mkvSE/aO6qC+TykR5LR"));
|
||||
}
|
||||
|
||||
private static final DESUtil DES = DESUtil.getInstance();
|
||||
private static final String DES_KEY = "#f$ddw4aFF2Wfgaewdff#GR0(DSFW@#?!@23#!@#a";
|
||||
|
||||
public static String encrypt(String str) {
|
||||
try {
|
||||
return DES.encryptStr(str, DES_KEY);
|
||||
} catch (Exception e) {
|
||||
System.out.println("加密充值通道时出错");
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String decrypt(String str) {
|
||||
try {
|
||||
return DES.decryptStr(str, DES_KEY);
|
||||
} catch (Exception e) {
|
||||
System.out.println("解密充值通道时出错");
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package javautils.encrypt;
|
||||
|
||||
/**
|
||||
* protect the password user inputed
|
||||
*/
|
||||
public class SHACode {
|
||||
private static final long SH0 = 0x67452301L;
|
||||
private static final long SH1 = 0xefcdab89L;
|
||||
private static final long SH2 = 0x98badcfeL;
|
||||
private static final long SH3 = 0x10325476L;
|
||||
private static final long SH4 = 0xc3d2e1f0L;
|
||||
|
||||
private static final long K0 = 0x5a827999L;
|
||||
private static final long K1 = 0x6ed9eba1L;
|
||||
private static final long K2 = 0x8f1bbcdcL;
|
||||
private static final long K3 = 0xca62c1d6L;
|
||||
|
||||
// df debug 12.11
|
||||
private static long[] W;
|
||||
private static byte[] BW;
|
||||
|
||||
private static int p0, p1, p2, p3, p4;
|
||||
private static long A, B, C, D, E, temp;
|
||||
|
||||
private static long f0(long x, long y, long z) {
|
||||
return (z ^ (x & (y ^ z)));
|
||||
}
|
||||
|
||||
private static long f1(long x, long y, long z) {
|
||||
return (x ^ y ^ z);
|
||||
}
|
||||
|
||||
private static long f2(long x, long y, long z) {
|
||||
return ((x & y) | (z & (x | y)));
|
||||
}
|
||||
|
||||
private static long f3(long x, long y, long z) {
|
||||
return (x ^ y ^ z);
|
||||
}
|
||||
|
||||
private static long S(int n, long X) {
|
||||
long tem = 0;
|
||||
X = X & 0x00000000FFFFFFFF;
|
||||
|
||||
if (n == 1) {
|
||||
tem = ((X >> 31) & 0x00000001);
|
||||
|
||||
}
|
||||
if (n == 5)
|
||||
tem = ((X >> 27) & 0x0000001F);
|
||||
if (n == 30)
|
||||
tem = ((X >> 2) & 0x3FFFFFFF);
|
||||
|
||||
return ((X << n) | tem);
|
||||
|
||||
}
|
||||
|
||||
private static void r0(int f, long K) {
|
||||
|
||||
temp = S(5, A) + f0(B, C, D) + E + W[p0++] + K;
|
||||
E = D;
|
||||
D = C;
|
||||
C = S(30, B);
|
||||
B = A;
|
||||
A = temp;
|
||||
}
|
||||
|
||||
private static void r1(int f, long K) {
|
||||
|
||||
temp = (W[p1++] ^ W[p2++] ^ W[p3++] ^ W[p4++]);
|
||||
|
||||
switch (f) {
|
||||
case 0:
|
||||
temp = S(5, A) + f0(B, C, D) + E + (W[p0++] = S(1, temp)) + K;
|
||||
break;
|
||||
case 1:
|
||||
temp = S(5, A) + f1(B, C, D) + E + (W[p0++] = S(1, temp)) + K;
|
||||
break;
|
||||
case 2:
|
||||
temp = S(5, A) + f2(B, C, D) + E + (W[p0++] = S(1, temp)) + K;
|
||||
break;
|
||||
case 3:
|
||||
temp = S(5, A) + f3(B, C, D) + E + (W[p0++] = S(1, temp)) + K;
|
||||
break;
|
||||
}
|
||||
|
||||
E = D;
|
||||
D = C;
|
||||
C = S(30, B);
|
||||
B = A;
|
||||
A = temp;
|
||||
}
|
||||
|
||||
public static long getCode(String mem) {
|
||||
int i, nread, nbits;
|
||||
int length = mem.toCharArray().length;
|
||||
int hi_length, lo_length;
|
||||
int padded;
|
||||
char[] s;
|
||||
int sp = 0;
|
||||
long h0, h1, h2, h3, h4;
|
||||
W = new long[80];
|
||||
BW = new byte[320];
|
||||
padded = 0;
|
||||
s = mem.toCharArray();
|
||||
h0 = SH0;
|
||||
h1 = SH1;
|
||||
h2 = SH2;
|
||||
h3 = SH3;
|
||||
h4 = SH4;
|
||||
for (hi_length = lo_length = 0;;) {
|
||||
if (length < 64)
|
||||
nread = length;
|
||||
else
|
||||
nread = 64;
|
||||
length -= nread;
|
||||
for (int m = 0; m < nread; m++)
|
||||
BW[m] = (byte) s[sp++];
|
||||
if (nread < 64) {
|
||||
nbits = nread * 8;
|
||||
|
||||
if ((lo_length += nbits) < (long) nbits)
|
||||
hi_length++;
|
||||
if ((nread < 64) && (padded == 0)) {
|
||||
BW[nread++] = (byte) 0x080;
|
||||
padded = 1;
|
||||
}
|
||||
|
||||
for (i = nread; i < 64; i++)
|
||||
BW[i] = 0;
|
||||
|
||||
byte[] tar = new byte[4];
|
||||
for (int z = 0; z < 64; z = z + 4) {
|
||||
for (int y = 0; y < 4; y++)
|
||||
tar[y] = BW[z + y];
|
||||
|
||||
W[z >> 2] = 0;
|
||||
W[z >> 2] = (W[z >> 2] | tar[0]) << 8;
|
||||
W[z >> 2] = (W[z >> 2] | (tar[1] & 0x00FF)) << 8;
|
||||
W[z >> 2] = ((W[z >> 2] | (tar[2] & 0x00FF)) << 8)
|
||||
| (tar[3] & 0x00FF);
|
||||
}
|
||||
|
||||
if (nread <= 56) {
|
||||
W[14] = hi_length;
|
||||
W[15] = lo_length;
|
||||
}
|
||||
} else {
|
||||
if ((lo_length += 512) < 512)
|
||||
hi_length++;
|
||||
|
||||
byte[] tar = new byte[4];
|
||||
for (int z = 0; z < 64; z = z + 4) {
|
||||
for (int y = 0; y < 4; y++)
|
||||
tar[y] = BW[z + y];
|
||||
|
||||
W[z >> 2] = 0;
|
||||
W[z >> 2] = (W[z >> 4] | tar[0]) << 8;
|
||||
W[z >> 2] = (W[z >> 2] | (tar[1] & 0x00FF)) << 8;
|
||||
W[z >> 2] = ((W[z >> 2] | (tar[2] & 0x00FF)) << 8)
|
||||
| (tar[3] & 0x00FF);
|
||||
}
|
||||
}
|
||||
p0 = 0;
|
||||
A = h0;
|
||||
B = h1;
|
||||
C = h2;
|
||||
D = h3;
|
||||
E = h4;
|
||||
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
r0(0, K0);
|
||||
|
||||
p1 = 13;
|
||||
p2 = 8;
|
||||
p3 = 2;
|
||||
p4 = 0;
|
||||
r1(0, K0);
|
||||
r1(0, K0);
|
||||
r1(0, K0);
|
||||
r1(0, K0);
|
||||
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
r1(1, K1);
|
||||
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
r1(2, K2);
|
||||
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
r1(3, K3);
|
||||
|
||||
h0 += A;
|
||||
h1 += B;
|
||||
h2 += C;
|
||||
h3 += D;
|
||||
h4 += E;
|
||||
|
||||
// System.gc();
|
||||
if (nread <= 56)
|
||||
break;
|
||||
}
|
||||
|
||||
W = null;
|
||||
BW = null;
|
||||
s = null;
|
||||
A = 0;
|
||||
B = 0;
|
||||
C = 0;
|
||||
D = 0;
|
||||
E = 0;
|
||||
temp = 0;
|
||||
h4 = 0;
|
||||
h3 = 0;
|
||||
h2 = 0;
|
||||
h1 = 0;
|
||||
p0 = 0;
|
||||
p1 = 0;
|
||||
p2 = 0;
|
||||
p3 = 0;
|
||||
p4 = 0;
|
||||
|
||||
int highBit, lowBit;
|
||||
|
||||
lowBit = (int) (h0 & 0x0FFFF);
|
||||
highBit = (int) ((h0 >> 16) & 0x0FFFFF);
|
||||
h0 = 0;
|
||||
String shaHigh = new String(Integer.toHexString(highBit));
|
||||
|
||||
int leng = shaHigh.length();
|
||||
if (leng > 4) {
|
||||
shaHigh = shaHigh.substring(leng - 4);
|
||||
|
||||
} else if (leng < 4) {
|
||||
for (int m = 0; m < 4 - leng; m++)
|
||||
shaHigh = "0" + shaHigh;
|
||||
}
|
||||
|
||||
String shaLow = new String(Integer.toHexString(lowBit));
|
||||
|
||||
leng = shaLow.length();
|
||||
if (leng > 4) {
|
||||
shaLow = shaLow.substring(leng - 4);
|
||||
|
||||
} else if (leng < 4) {
|
||||
for (int m = 0; m < 4 - leng; m++)
|
||||
shaLow = "0" + shaLow;
|
||||
}
|
||||
return Long.parseLong(shaHigh + shaLow, 16);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package javautils.encrypt;
|
||||
|
||||
import javautils.date.Moment;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.apache.commons.lang3.RandomStringUtils;
|
||||
|
||||
/**
|
||||
* Created by Nick on 2017-06-28.
|
||||
*/
|
||||
public class TokenUtil {
|
||||
/**
|
||||
* 生成一次性使用的token
|
||||
* @return
|
||||
*/
|
||||
public static String generateDisposableToken() {
|
||||
String tokenStr = new Moment().format("yyyyMMddHHmmss") + RandomStringUtils.random(8, true, true);
|
||||
tokenStr = DigestUtils.md5Hex(tokenStr).toUpperCase();
|
||||
return tokenStr;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package javautils.encrypt;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
|
||||
/**
|
||||
* Created by Nick on 2017-07-01.
|
||||
*/
|
||||
public class URLEncodeUtil {
|
||||
public static String encode(String str, String charset){
|
||||
try {
|
||||
return URLEncoder.encode(str, charset);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
public static String decode(String str, String charset){
|
||||
try {
|
||||
return URLDecoder.decode(str, charset);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return str;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package javautils.encrypt;
|
||||
|
||||
import lottery.domains.content.entity.UserBetsOriginal;
|
||||
import org.apache.commons.codec.digest.DigestUtils;
|
||||
import org.apache.commons.lang.RandomStringUtils;
|
||||
|
||||
/**
|
||||
* Created by Nick on 2017/1/15.
|
||||
*/
|
||||
public class UserBetsEncrypt {
|
||||
private static final DESUtil DES = DESUtil.getInstance();
|
||||
private static final String DES_KEY = "#$ddw4FFWfg#GR0(DSFW@#?!@#!@#$C$$3GhyUhb";
|
||||
|
||||
public static String encryptCertification(String certification) {
|
||||
return DES.encryptStr(certification, DES_KEY);
|
||||
}
|
||||
|
||||
public static String getRandomCertification() {
|
||||
return RandomStringUtils.random(10, true, true);
|
||||
}
|
||||
|
||||
public static String getIdentification(UserBetsOriginal original, String certification) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
|
||||
int point = Double.valueOf(original.getPoint()).intValue();
|
||||
int money = Double.valueOf(original.getMoney()).intValue();
|
||||
|
||||
sb.append(original.getId())
|
||||
.append(original.getBillno())
|
||||
.append(original.getUserId())
|
||||
.append(original.getType())
|
||||
.append(original.getLotteryId())
|
||||
.append(original.getExpect())
|
||||
.append(original.getRuleId())
|
||||
.append(DigestUtils.md5Hex(original.getCodes()))
|
||||
.append(original.getNums())
|
||||
.append(original.getModel())
|
||||
.append(original.getMultiple())
|
||||
.append(original.getCode())
|
||||
.append(point)
|
||||
.append(money)
|
||||
.append(original.getTime())
|
||||
.append(original.getStopTime())
|
||||
.append(original.getOpenTime())
|
||||
.append(original.getStatus())
|
||||
.append(original.getOpenCode())
|
||||
.append(original.getPrizeMoney())
|
||||
.append(original.getPrizeTime())
|
||||
.append(original.getChaseBillno())
|
||||
.append(original.getChaseBillno())
|
||||
.append(original.getPlanBillno())
|
||||
.append(original.getRewardMoney())
|
||||
.append(certification);
|
||||
|
||||
String thisData = sb.toString();
|
||||
return DigestUtils.md5Hex(thisData + certification);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package javautils.http;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Http Cookie
|
||||
*/
|
||||
public class CookieUtil {
|
||||
|
||||
protected static final Logger logger = LoggerFactory.getLogger(CookieUtil.class);
|
||||
|
||||
private static CookieUtil instance;
|
||||
|
||||
private CookieUtil(){
|
||||
|
||||
}
|
||||
|
||||
private static synchronized void synInit() {
|
||||
if(instance == null) {
|
||||
instance = new CookieUtil();
|
||||
}
|
||||
}
|
||||
|
||||
public static CookieUtil getInstance(){
|
||||
if(instance == null) {
|
||||
synInit();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置cookie
|
||||
*
|
||||
* @param response
|
||||
* @param name
|
||||
* cookie名字
|
||||
* @param value
|
||||
* cookie值
|
||||
* @param maxAge
|
||||
* cookie生命周期 以秒为单位
|
||||
*/
|
||||
public void addCookie(HttpServletResponse response, String name,
|
||||
String value, int maxAge) {
|
||||
Cookie cookie = new Cookie(name, value);
|
||||
if (maxAge > 0) {
|
||||
cookie.setMaxAge(maxAge);
|
||||
}
|
||||
response.addCookie(cookie);
|
||||
logger.debug(name + ":Cookie已经设置");
|
||||
}
|
||||
|
||||
/**
|
||||
* 立刻使cookie失效
|
||||
* @param request
|
||||
* @param name
|
||||
*/
|
||||
public void cleanCookie(HttpServletRequest request, HttpServletResponse response, String name) {
|
||||
Cookie cookie = getCookieByName(request, name);
|
||||
if(cookie != null) {
|
||||
cookie.setMaxAge(0);
|
||||
response.addCookie(cookie);
|
||||
logger.debug(name + ":Cookie已经删除");
|
||||
} else {
|
||||
logger.debug(name + ":Cookie为空");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据名字获取cookie
|
||||
*
|
||||
* @param request
|
||||
* @param name
|
||||
* cookie名字
|
||||
* @return
|
||||
*/
|
||||
public Cookie getCookieByName(HttpServletRequest request, String name) {
|
||||
Map<String, Cookie> cookieMap = ReadCookieMap(request);
|
||||
if (cookieMap.containsKey(name)) {
|
||||
Cookie cookie = (Cookie) cookieMap.get(name);
|
||||
return cookie;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将cookie封装到Map里面
|
||||
*
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
public Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
|
||||
Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (cookies != null) {
|
||||
for (Cookie cookie : cookies) {
|
||||
cookieMap.put(cookie.getName(), cookie);
|
||||
}
|
||||
}
|
||||
return cookieMap;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
package javautils.http;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.conn.ConnectionKeepAliveStrategy;
|
||||
import org.apache.http.entity.InputStreamEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* http通用工具类,适用普通https和http(非连接池),如果是带ssl密码的,请参考{@link lottery.domains.content.api.pt.PTAPI}
|
||||
* Created by Nick on 2017-06-15.
|
||||
*/
|
||||
public class HttpClientUtil {
|
||||
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class); //日志记录
|
||||
|
||||
private static CloseableHttpClient getHttpClient(int timeout) {
|
||||
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
|
||||
|
||||
// 是否要keep alive
|
||||
ConnectionKeepAliveStrategy keepAliveStrategy = HttpConfigBuilder.getInstance().buildKeepAliveStrategy(60 * 1000);
|
||||
clientBuilder.setKeepAliveStrategy(keepAliveStrategy);
|
||||
|
||||
RequestConfig requestConfig = HttpConfigBuilder.getInstance().buildRequestConfig(timeout);
|
||||
clientBuilder.setDefaultRequestConfig(requestConfig);
|
||||
|
||||
// 连接池
|
||||
// PoolingHttpClientConnectionManager connMgr = HttpConfigBuilder.getInstance().buildPoolingHttpClientConnectionManager(100, 100);
|
||||
// clientBuilder.setConnectionManager(connMgr);
|
||||
|
||||
CloseableHttpClient httpClient = clientBuilder.build();
|
||||
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
private static CloseableHttpClient getHttpsClient(int timeout, String sslVersion) throws NoSuchAlgorithmException, KeyManagementException {
|
||||
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
|
||||
|
||||
// 是否要keep alive
|
||||
ConnectionKeepAliveStrategy keepAliveStrategy = HttpConfigBuilder.getInstance().buildKeepAliveStrategy(60 * 1000);
|
||||
clientBuilder.setKeepAliveStrategy(keepAliveStrategy);
|
||||
|
||||
RequestConfig requestConfig = HttpConfigBuilder.getInstance().buildRequestConfig(timeout);
|
||||
clientBuilder.setDefaultRequestConfig(requestConfig);
|
||||
|
||||
// ssl连接
|
||||
BasicHttpClientConnectionManager connMgr;
|
||||
if (sslVersion == null) {
|
||||
connMgr = HttpConfigBuilder.getInstance().buildBasicHttpsClientConnectionManager();
|
||||
}
|
||||
else {
|
||||
connMgr = HttpConfigBuilder.getInstance().buildBasicHttpsClientConnectionManager(sslVersion);
|
||||
}
|
||||
clientBuilder.setConnectionManager(connMgr);
|
||||
|
||||
CloseableHttpClient httpClient = clientBuilder.build();
|
||||
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
public static String get(String url ,Map<String ,String > httpHeader, int timeout) throws Exception{
|
||||
CloseableHttpClient httpClient;
|
||||
if (url.startsWith("https://")) {
|
||||
httpClient = getHttpsClient(timeout, null);
|
||||
}
|
||||
else {
|
||||
httpClient = getHttpClient(timeout);
|
||||
}
|
||||
|
||||
return get(httpClient, url, httpHeader);
|
||||
}
|
||||
|
||||
public static String get(CloseableHttpClient httpClient, String url ,Map<String ,String > httpHeader) throws IOException{
|
||||
String strResult = null;
|
||||
try {
|
||||
//发送get请求
|
||||
HttpGet request = new HttpGet(url);
|
||||
|
||||
//设置http头参数
|
||||
if(httpHeader!=null && httpHeader.size()>0){
|
||||
for(Iterator<Map.Entry<String, String>> ies = httpHeader.entrySet().iterator(); ies.hasNext();){
|
||||
Map.Entry<String, String> entry = ies.next();
|
||||
String key =entry.getKey();
|
||||
String value = entry.getValue();
|
||||
request.addHeader(key, value);
|
||||
}
|
||||
}
|
||||
CloseableHttpResponse response = httpClient.execute(request);
|
||||
|
||||
/**请求发送成功,并得到响应**/
|
||||
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
|
||||
try {
|
||||
/**读取服务器返回过来的json字符串数据**/
|
||||
strResult = EntityUtils.toString(response.getEntity(),"UTF-8");
|
||||
url = URLDecoder.decode(url, "UTF-8");
|
||||
}catch(Exception e) {
|
||||
logger.error("get请求提交失败:" + url);
|
||||
}finally {
|
||||
response.close();
|
||||
}
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
logger.error("get请求提交失败:" + url, e);
|
||||
} finally {
|
||||
httpClient.close();
|
||||
}
|
||||
return strResult;
|
||||
}
|
||||
|
||||
public static String post(String url, Map<String, String> params, Map<String, String> headers, int timeout) throws Exception{
|
||||
CloseableHttpClient httpClient;
|
||||
if (url.startsWith("https://")) {
|
||||
httpClient = getHttpsClient(timeout, null);
|
||||
}
|
||||
else {
|
||||
httpClient = getHttpClient(timeout);
|
||||
}
|
||||
|
||||
return post(httpClient, url, params, headers);
|
||||
}
|
||||
|
||||
public static String postAsStream(String url, Map<String, String> params, Map<String, String> headers, int timeout) throws Exception{
|
||||
CloseableHttpClient httpClient;
|
||||
if (url.startsWith("https://")) {
|
||||
httpClient = getHttpsClient(timeout, null);
|
||||
}
|
||||
else {
|
||||
httpClient = getHttpClient(timeout);
|
||||
}
|
||||
|
||||
return postAsStream(httpClient, url, params, headers);
|
||||
}
|
||||
|
||||
public static String postAsStream(String url, String content, Map<String, String> headers, int timeout) throws Exception{
|
||||
CloseableHttpClient httpClient;
|
||||
if (url.startsWith("https://")) {
|
||||
httpClient = getHttpsClient(timeout, null);
|
||||
}
|
||||
else {
|
||||
httpClient = getHttpClient(timeout);
|
||||
}
|
||||
|
||||
return postAsStream(httpClient, url, content, headers);
|
||||
}
|
||||
|
||||
public static String postSSL(String url, Map<String, String> params, Map<String, String> headers, int timeout, String sslVersion) throws Exception{
|
||||
CloseableHttpClient httpClient;
|
||||
if (url.startsWith("https://")) {
|
||||
httpClient = getHttpsClient(timeout, sslVersion);
|
||||
}
|
||||
else {
|
||||
httpClient = getHttpClient(timeout);
|
||||
}
|
||||
|
||||
return post(httpClient, url, params, headers);
|
||||
}
|
||||
|
||||
public static String post(CloseableHttpClient httpClient, String url, Map<String, String> params, Map<String, String> headers) throws IOException {
|
||||
String result = null;
|
||||
try {
|
||||
HttpPost request = new HttpPost(url);
|
||||
|
||||
//设置http头参数
|
||||
if(headers!=null && headers.size()>0) {
|
||||
for(Iterator<Map.Entry<String, String>> ies = headers.entrySet().iterator(); ies.hasNext();){
|
||||
Map.Entry<String, String> entry = ies.next();
|
||||
|
||||
String key =entry.getKey();
|
||||
String value = entry.getValue();
|
||||
|
||||
request.addHeader(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
if (params != null && params.size() > 0) {
|
||||
List list = new ArrayList();
|
||||
Iterator iterator = params.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry elem = (Map.Entry) iterator.next();
|
||||
list.add(new BasicNameValuePair((String) elem.getKey(), (String) elem.getValue()));
|
||||
}
|
||||
if (list.size() > 0) {
|
||||
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "utf-8");
|
||||
request.setEntity(entity);
|
||||
}
|
||||
}
|
||||
|
||||
CloseableHttpResponse response = httpClient.execute(request);
|
||||
url = URLDecoder.decode(url, "UTF-8");
|
||||
|
||||
/**请求发送成功,并得到响应**/
|
||||
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
|
||||
try {
|
||||
/**读取服务器返回过来的字符串数据**/
|
||||
result = EntityUtils.toString(response.getEntity(),"UTF-8");
|
||||
} catch (Exception e) {
|
||||
logger.error("post请求提交失败:" + url, e);
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
} else {
|
||||
result = response.getStatusLine().getStatusCode()+"-"+response.getStatusLine().getReasonPhrase();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("post请求提交失败:" + url, e);
|
||||
} finally{
|
||||
httpClient.close();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String postAsStream(CloseableHttpClient httpClient, String url, Map<String, String> params, Map<String, String> headers) throws IOException {
|
||||
String result = null;
|
||||
try {
|
||||
HttpPost request = new HttpPost(url);
|
||||
|
||||
//设置http头参数
|
||||
if(headers!=null && headers.size()>0) {
|
||||
for(Iterator<Map.Entry<String, String>> ies = headers.entrySet().iterator(); ies.hasNext();){
|
||||
Map.Entry<String, String> entry = ies.next();
|
||||
|
||||
String key =entry.getKey();
|
||||
String value = entry.getValue();
|
||||
|
||||
request.addHeader(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
if (params != null && params.size() > 0) {
|
||||
String paramUrl = UrlParamUtils.toUrlParam(params);
|
||||
InputStream is = new ByteArrayInputStream(paramUrl.getBytes());
|
||||
InputStreamEntity inputEntry = new InputStreamEntity(is);
|
||||
request.setEntity(inputEntry);
|
||||
}
|
||||
|
||||
CloseableHttpResponse response = httpClient.execute(request);
|
||||
url = URLDecoder.decode(url, "UTF-8");
|
||||
|
||||
/**请求发送成功,并得到响应**/
|
||||
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
|
||||
try {
|
||||
/**读取服务器返回过来的字符串数据**/
|
||||
result = EntityUtils.toString(response.getEntity(),"UTF-8");
|
||||
} catch (Exception e) {
|
||||
logger.error("post请求提交失败:" + url, e);
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
} else {
|
||||
result = response.getStatusLine().getStatusCode()+"-"+response.getStatusLine().getReasonPhrase();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("post请求提交失败:" + url, e);
|
||||
} finally{
|
||||
httpClient.close();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String postAsStream(CloseableHttpClient httpClient, String url, String content, Map<String, String> headers) throws IOException {
|
||||
String result = null;
|
||||
try {
|
||||
HttpPost request = new HttpPost(url);
|
||||
|
||||
//设置http头参数
|
||||
if(headers!=null && headers.size()>0) {
|
||||
for(Iterator<Map.Entry<String, String>> ies = headers.entrySet().iterator(); ies.hasNext();){
|
||||
Map.Entry<String, String> entry = ies.next();
|
||||
|
||||
String key =entry.getKey();
|
||||
String value = entry.getValue();
|
||||
|
||||
request.addHeader(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
InputStream is = new ByteArrayInputStream(content.getBytes());
|
||||
InputStreamEntity inputEntry = new InputStreamEntity(is);
|
||||
request.setEntity(inputEntry);
|
||||
|
||||
CloseableHttpResponse response = httpClient.execute(request);
|
||||
url = URLDecoder.decode(url, "UTF-8");
|
||||
|
||||
/**请求发送成功,并得到响应**/
|
||||
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
|
||||
try {
|
||||
/**读取服务器返回过来的字符串数据**/
|
||||
result = EntityUtils.toString(response.getEntity(),"UTF-8");
|
||||
} catch (Exception e) {
|
||||
logger.error("post请求提交失败:" + url, e);
|
||||
} finally {
|
||||
response.close();
|
||||
}
|
||||
} else {
|
||||
result = response.getStatusLine().getStatusCode()+"-"+response.getStatusLine().getReasonPhrase();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("post请求提交失败:" + url, e);
|
||||
} finally{
|
||||
httpClient.close();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String doPost(String url) {
|
||||
CloseableHttpClient httpClient = null;
|
||||
CloseableHttpResponse response = null;
|
||||
String result = "";
|
||||
try {
|
||||
// 通过址默认配置创建一个httpClient实例
|
||||
httpClient = HttpClients.createDefault();
|
||||
// 创建httpGet远程连接实例
|
||||
HttpPost httpGet = new HttpPost(url);
|
||||
// 设置请求头信息,鉴权
|
||||
httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
|
||||
// 设置配置请求参数
|
||||
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
|
||||
.setConnectionRequestTimeout(35000)// 请求超时时间
|
||||
.setSocketTimeout(60000)// 数据读取超时时间
|
||||
.build();
|
||||
// 为httpGet实例设置配置
|
||||
httpGet.setConfig(requestConfig);
|
||||
// 执行get请求得到返回对象
|
||||
response = httpClient.execute(httpGet);
|
||||
// 通过返回对象获取返回数据
|
||||
HttpEntity entity = response.getEntity();
|
||||
// 通过EntityUtils中的toString方法将结果转换为字符串
|
||||
result = EntityUtils.toString(entity);
|
||||
} catch (ClientProtocolException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
// 关闭资源
|
||||
if (null != response) {
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (null != httpClient) {
|
||||
try {
|
||||
httpClient.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package javautils.http;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpRequestRetryHandler;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.config.Registry;
|
||||
import org.apache.http.config.RegistryBuilder;
|
||||
import org.apache.http.conn.ConnectionKeepAliveStrategy;
|
||||
import org.apache.http.conn.socket.ConnectionSocketFactory;
|
||||
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
|
||||
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
import org.apache.http.protocol.HttpContext;
|
||||
|
||||
import javax.net.ssl.*;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.security.*;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
|
||||
/**
|
||||
* http 配置
|
||||
* @author Nick
|
||||
* @since 2015-10-2
|
||||
*/
|
||||
public class HttpConfigBuilder {
|
||||
private static final HttpConfigBuilder INSTANCE = new HttpConfigBuilder();
|
||||
private HttpConfigBuilder() {
|
||||
}
|
||||
|
||||
public static HttpConfigBuilder getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
public ConnectionKeepAliveStrategy buildKeepAliveStrategy(final long duration) {
|
||||
return new ConnectionKeepAliveStrategy() {
|
||||
@Override
|
||||
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
|
||||
return duration;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public HttpRequestRetryHandler buildRetryHandler(final int retryCount) {
|
||||
return new DefaultHttpRequestRetryHandler(retryCount, false);
|
||||
}
|
||||
|
||||
public RequestConfig buildRequestConfig(final int timeout) {
|
||||
return RequestConfig.custom().setConnectionRequestTimeout(timeout).setConnectTimeout(timeout).setSocketTimeout(timeout).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建单个http连接
|
||||
*/
|
||||
public BasicHttpClientConnectionManager buildBasicHttpClientConnectionManager() {
|
||||
BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
|
||||
return connectionManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建单个https连接,信任所有
|
||||
*/
|
||||
public BasicHttpClientConnectionManager buildBasicHttpsClientConnectionManager() {
|
||||
try {
|
||||
TrustManager[] trustAllCerts = new TrustManager[] {
|
||||
new X509TrustManager() {
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
|
||||
|
||||
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||
sslContext.init(null, trustAllCerts, new SecureRandom());
|
||||
|
||||
HostnameVerifier allHostsValid = new HostnameVerifier() {
|
||||
public boolean verify(String hostname, SSLSession session) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, allHostsValid);
|
||||
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("http", PlainConnectionSocketFactory.getSocketFactory())
|
||||
.register("https", sslSocketFactory)
|
||||
.build();
|
||||
BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager(socketFactoryRegistry);
|
||||
return connMgr;
|
||||
} catch (KeyManagementException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化https连接出错");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化https连接出错");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建单个https连接,信任所有
|
||||
*/
|
||||
public BasicHttpClientConnectionManager buildBasicHttpsClientConnectionManager(String sslVersion) {
|
||||
try {
|
||||
TrustManager[] trustAllCerts = new TrustManager[] {
|
||||
new X509TrustManager() {
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
|
||||
|
||||
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||
sslContext.init(null, trustAllCerts, new SecureRandom());
|
||||
|
||||
HostnameVerifier allHostsValid = new HostnameVerifier() {
|
||||
public boolean verify(String hostname, SSLSession session) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[]{sslVersion}, null, allHostsValid);
|
||||
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("http", PlainConnectionSocketFactory.getSocketFactory())
|
||||
.register("https", sslSocketFactory)
|
||||
.build();
|
||||
BasicHttpClientConnectionManager connMgr = new BasicHttpClientConnectionManager(socketFactoryRegistry);
|
||||
return connMgr;
|
||||
} catch (KeyManagementException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化https连接出错");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化https连接出错");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建https连接池,信任所有
|
||||
*/
|
||||
public PoolingHttpClientConnectionManager buildPoolingHttpsClientConnectionManager(final int maxTotal, final int defaultMaxPerRoute) {
|
||||
try {
|
||||
TrustManager[] trustAllCerts = new TrustManager[] {
|
||||
new X509TrustManager() {
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
|
||||
|
||||
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||
sslContext.init(null, trustAllCerts, new SecureRandom());
|
||||
|
||||
HostnameVerifier allHostsValid = new HostnameVerifier() {
|
||||
public boolean verify(String hostname, SSLSession session) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, allHostsValid);
|
||||
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("http", PlainConnectionSocketFactory.getSocketFactory())
|
||||
.register("https", sslSocketFactory)
|
||||
.build();
|
||||
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
|
||||
connectionManager.setMaxTotal(maxTotal);
|
||||
connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
|
||||
return connectionManager;
|
||||
} catch (KeyManagementException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化https连接出错");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化https连接出错");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建普通http连接池
|
||||
*/
|
||||
public PoolingHttpClientConnectionManager buildPoolingHttpClientConnectionManager(final int maxTotal, final int defaultMaxPerRoute) {
|
||||
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
|
||||
connectionManager.setMaxTotal(maxTotal);
|
||||
connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
|
||||
return connectionManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建带SSL证书密码的连接池
|
||||
*/
|
||||
public PoolingHttpClientConnectionManager buildP12PoolingHttpClientConnectionManager(final int maxTotal, final int defaultMaxPerRoute, File p12File, String pwd) {
|
||||
try {
|
||||
KeyStore ks = KeyStore.getInstance("PKCS12");
|
||||
FileInputStream fis = new FileInputStream(p12File);
|
||||
ks.load(fis, pwd.toCharArray());
|
||||
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
|
||||
kmf.init(ks, pwd.toCharArray());
|
||||
KeyManager[] kms = kmf.getKeyManagers();
|
||||
|
||||
//Crete TrustManager to bypass trusted certificate check
|
||||
TrustManager[] trustAllCerts = new TrustManager[] {
|
||||
new X509TrustManager() {
|
||||
public X509Certificate[] getAcceptedIssuers() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
|
||||
|
||||
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||
sslContext.init(kms, trustAllCerts, new SecureRandom());
|
||||
|
||||
HostnameVerifier allHostsValid = new HostnameVerifier() {
|
||||
public boolean verify(String hostname, SSLSession session) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, allHostsValid);
|
||||
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
|
||||
.register("http", PlainConnectionSocketFactory.getSocketFactory())
|
||||
.register("https", sslSocketFactory)
|
||||
.build();
|
||||
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry);
|
||||
connMgr.setMaxTotal(maxTotal);
|
||||
connMgr.setDefaultMaxPerRoute(defaultMaxPerRoute);
|
||||
|
||||
return connMgr;
|
||||
} catch (KeyStoreException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化P12连接出错");
|
||||
} catch (CertificateException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化P12连接出错");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化P12连接出错");
|
||||
} catch (FileNotFoundException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化P12连接出错");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化P12连接出错");
|
||||
} catch (UnrecoverableKeyException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化P12连接出错");
|
||||
} catch (KeyManagementException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("初始化P12连接出错");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
package javautils.http;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
|
||||
import javautils.StringUtil;
|
||||
import lottery.web.WebJSON;
|
||||
|
||||
/**
|
||||
* Http工具类
|
||||
*/
|
||||
public class HttpUtil {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
|
||||
|
||||
public static final String json = "text/json";
|
||||
public static final String html = "text/html";
|
||||
public static final String xml = "text/xml";
|
||||
|
||||
public static void write(HttpServletResponse response, String s) {
|
||||
logger.debug(s);
|
||||
if (StringUtil.isNotNull(s)) {
|
||||
try {
|
||||
response.setCharacterEncoding("utf-8");
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.write(s);
|
||||
writer.flush();
|
||||
writer.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void write(HttpServletResponse response, String s,
|
||||
String ContentType) {
|
||||
logger.debug(s);
|
||||
if (StringUtil.isNotNull(s)) {
|
||||
try {
|
||||
response.setContentType(ContentType);
|
||||
response.setCharacterEncoding("utf-8");
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.write(s);
|
||||
writer.flush();
|
||||
writer.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void writeJSONP(HttpServletRequest request,
|
||||
HttpServletResponse response, String s, String ContentType) {
|
||||
String callback = request.getParameter("callback");
|
||||
logger.debug(s);
|
||||
if (StringUtil.isNotNull(s)) {
|
||||
try {
|
||||
String callbackStr = callback + "(" + s + ")"; // 跨域请求用
|
||||
response.setContentType(ContentType);
|
||||
response.setCharacterEncoding("utf-8");
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.write(callbackStr);
|
||||
writer.flush();
|
||||
writer.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void writeJSONP(HttpServletRequest request,
|
||||
HttpServletResponse response, String s) {
|
||||
String callback = request.getParameter("callback");
|
||||
logger.debug(s);
|
||||
if (StringUtil.isNotNull(s)) {
|
||||
try {
|
||||
String callbackStr = callback + "(" + s + ")"; // 跨域请求用
|
||||
response.setCharacterEncoding("utf-8");
|
||||
PrintWriter writer = response.getWriter();
|
||||
writer.write(callbackStr);
|
||||
writer.flush();
|
||||
writer.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static String getWebDomainPath(HttpServletRequest request) {
|
||||
String name = request.getServerName();
|
||||
if("localhost".equals(name)) {
|
||||
name = "127.0.0.1";
|
||||
}
|
||||
int port = request.getServerPort();
|
||||
if(port == 80) {
|
||||
return "http://" + name;
|
||||
} else {
|
||||
return "http://" + name + ":" + port;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getWebPath(HttpServletRequest request) {
|
||||
String path = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + request.getServletPath();
|
||||
return path;
|
||||
}
|
||||
|
||||
public static String getRequestPath(HttpServletRequest request) {
|
||||
String path = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + request.getServletPath();
|
||||
String queryStr = request.getQueryString();
|
||||
if(StringUtil.isNotNull(queryStr)) {
|
||||
path += "?" + queryStr;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
public static Map<String, String> getRequestMap(String queryStr) {
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
if(StringUtil.isNotNull(queryStr)) {
|
||||
String[] strs = queryStr.split("&");
|
||||
for (String str : strs) {
|
||||
String[] keyValue = str.split("=");
|
||||
map.put(keyValue[0], keyValue[1]);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
public static String getRealIp(WebJSON json, HttpServletRequest request) {
|
||||
String ip = request.getHeader("x-forwarded-for");
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("HTTP_CLIENT_IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
|
||||
if(ip.split(",").length > 0) {
|
||||
ip = ip.split(",")[0];
|
||||
}
|
||||
/*
|
||||
if (!isLegalIPV4(ip)) {
|
||||
// 不是合法IPV4地址
|
||||
if (json != null) {
|
||||
json.set(2, "2-1092", ip);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
*/
|
||||
return ip;
|
||||
}
|
||||
|
||||
public static boolean isLegalIPV4(String ipv4) {
|
||||
if(ipv4 == null || ipv4.length()==0){
|
||||
return false; //字符串为空或者空串
|
||||
}
|
||||
|
||||
String[] parts=ipv4.split("\\.");//因为java doc里已经说明, split的参数是reg, 即正则表达式, 如果用"|"分割, 则需使用"\\|"
|
||||
if(parts.length != 4){
|
||||
return false;//分割开的数组根本就不是4个数字
|
||||
}
|
||||
for(int i=0; i<parts.length; i++){
|
||||
try{
|
||||
int n = Integer.parseInt(parts[i]);
|
||||
if(n<0 || n>255){
|
||||
return false;//数字不在正确范围内
|
||||
}
|
||||
}catch (NumberFormatException e) {
|
||||
return false;//转换数字不正确
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static String getHost(HttpServletRequest request) {
|
||||
return request.getScheme() + "://" + request.getHeader("Host").trim();
|
||||
}
|
||||
|
||||
public static String escapeInput(String s) {
|
||||
return HtmlUtils.htmlEscape(s);
|
||||
}
|
||||
|
||||
public static Short getShortParameter(HttpServletRequest request, String name) {
|
||||
String value = request.getParameter(name);
|
||||
try {
|
||||
return Short.parseShort(value);
|
||||
} catch (Exception e) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Integer getIntParameter(HttpServletRequest request, String name) {
|
||||
String value = request.getParameter(name);
|
||||
try {
|
||||
if (StringUtils.isEmpty(value)) {
|
||||
return null;
|
||||
}
|
||||
return Integer.parseInt(value);
|
||||
} catch (Exception e) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String getStringParameterTrim(HttpServletRequest request, String name) {
|
||||
String value = request.getParameter(name);
|
||||
try {
|
||||
if (value != null) return value.trim();
|
||||
return value;
|
||||
} catch (Exception e) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean isSpecialChar(String str) {
|
||||
String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t";
|
||||
Pattern p = Pattern.compile(regEx);
|
||||
Matcher m = p.matcher(str);
|
||||
return m.find();
|
||||
}
|
||||
|
||||
public static Boolean getBooleanParameter(HttpServletRequest request, String name) {
|
||||
String value = request.getParameter(name);
|
||||
try {
|
||||
if (StringUtils.isEmpty(value)) {
|
||||
return null;
|
||||
}
|
||||
return Boolean.parseBoolean(value);
|
||||
} catch (Exception e) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Double getDoubleParameter(HttpServletRequest request, String name) {
|
||||
String value = request.getParameter(name);
|
||||
try {
|
||||
if (StringUtils.isEmpty(value)) {
|
||||
return null;
|
||||
}
|
||||
return Double.parseDouble(value);
|
||||
} catch (Exception e) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Float getFloatParameter(HttpServletRequest request, String name) {
|
||||
String value = request.getParameter(name);
|
||||
try {
|
||||
if (StringUtils.isEmpty(value)) {
|
||||
return null;
|
||||
}
|
||||
return Float.parseFloat(value);
|
||||
} catch (Exception e) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Long getLongParameter(HttpServletRequest request, String name) {
|
||||
String value = request.getParameter(name);
|
||||
try {
|
||||
if (StringUtils.isEmpty(value)) {
|
||||
return null;
|
||||
}
|
||||
return Long.parseLong(value);
|
||||
} catch (Exception e) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String formatSessionId(final HttpSession session) {
|
||||
String id = session.getId();
|
||||
if(id.indexOf("!") != -1) {
|
||||
id = id.substring(0, id.indexOf("!"));
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
public static String encodeURL(String destURL) {
|
||||
try {
|
||||
destURL = URLEncoder.encode(destURL, "utf-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
}
|
||||
return destURL;
|
||||
}
|
||||
|
||||
public static String decodeURL(String destURL) {
|
||||
try {
|
||||
destURL = URLDecoder.decode(destURL, "utf-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
}
|
||||
return destURL;
|
||||
}
|
||||
|
||||
public static String getRequestURL(HttpServletRequest request) {
|
||||
boolean flag = true;
|
||||
String paramName, paramValue;
|
||||
StringBuffer requestURL = request.getRequestURL();
|
||||
Enumeration<?> paramNames = request.getParameterNames();
|
||||
while (paramNames.hasMoreElements()) {
|
||||
if (flag) {
|
||||
flag = false;
|
||||
requestURL.append("?");
|
||||
} else {
|
||||
requestURL.append("&");
|
||||
}
|
||||
paramName = (String) paramNames.nextElement();
|
||||
try {
|
||||
paramValue = URLEncoder.encode(request.getParameter(paramName), "utf-8");
|
||||
requestURL.append(paramName).append("=").append(paramValue);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
}
|
||||
}
|
||||
return requestURL.toString();
|
||||
}
|
||||
|
||||
public static void printHeaderFields(HttpURLConnection conn) {
|
||||
Map<String, List<String>> headerFields = conn.getHeaderFields();
|
||||
for (Object key : headerFields.keySet().toArray()) {
|
||||
System.out.println(key + ":" + headerFields.get(key).toString());
|
||||
for (String value : headerFields.get(key)) {
|
||||
System.out.println("==============:" + value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回http(s)://www.xxx.com
|
||||
*/
|
||||
public static String getReferer(HttpServletRequest request) {
|
||||
// return request.getScheme() + "://" + getServerName(request);
|
||||
return getSchema(request) + "://" + getServerName(request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取访问协议,nginx中需要配置 proxy_set_header X-Forwarded-Proto $scheme;
|
||||
*/
|
||||
public static String getSchema(HttpServletRequest request) {
|
||||
String schema = request.getHeader("X-Forwarded-Proto");
|
||||
if (!"http".equalsIgnoreCase(schema) && !"https".equalsIgnoreCase(schema)) {
|
||||
schema = request.getScheme();
|
||||
}
|
||||
return schema;
|
||||
}
|
||||
/**
|
||||
* 返回www.xxx.com
|
||||
*/
|
||||
public static String getServerName(HttpServletRequest request) {
|
||||
return request.getServerName();
|
||||
}
|
||||
|
||||
public static String getUserAgent(HttpServletRequest request) {
|
||||
return getHeader(request, "User-Agent");
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回经过过滤的http头
|
||||
*/
|
||||
public static String getHeader(HttpServletRequest request, String header) {
|
||||
String headerValue = request.getHeader(header);
|
||||
headerValue = HttpUtil.escapeInput(headerValue);
|
||||
return headerValue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package javautils.http;
|
||||
|
||||
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.http.client.HttpRequestRetryHandler;
|
||||
import org.apache.http.client.config.RequestConfig;
|
||||
import org.apache.http.conn.ConnectionKeepAliveStrategy;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
|
||||
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
|
||||
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* rest template构建器
|
||||
* @author Nick
|
||||
* @since 2015-10-2
|
||||
*/
|
||||
public class RestTemplateBuilder {
|
||||
private static final RestTemplateBuilder INSTANCE = new RestTemplateBuilder();
|
||||
private static final int DEFAULT_TIMEOUT = 3 * 1000; // 默认3秒超时
|
||||
private static final long DEFAULT_KEEPALIVE_DURATION = 60 * 1000; // 默认1分钟超时
|
||||
private static final int DEFAULT_RETRYCOUNT = 3; // 默认重试3次
|
||||
private static final int DEFAULT_MAX_TOTAL = 100;
|
||||
private static final int DEFAULT_MAX_PERROUTE = 50;
|
||||
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
|
||||
|
||||
private int timeout;
|
||||
private long keepaliveDuration;
|
||||
private int retrycount;
|
||||
private int maxTotal;
|
||||
private int maxPerroute;
|
||||
private String sslFile;
|
||||
private String sslFilePwd;
|
||||
|
||||
public RestTemplateBuilder() {
|
||||
this.timeout = DEFAULT_TIMEOUT;
|
||||
this.keepaliveDuration = DEFAULT_KEEPALIVE_DURATION;
|
||||
this.retrycount = DEFAULT_RETRYCOUNT;
|
||||
this.maxTotal = DEFAULT_MAX_TOTAL;
|
||||
this.maxPerroute = DEFAULT_MAX_PERROUTE;
|
||||
}
|
||||
|
||||
public RestTemplate build() {
|
||||
|
||||
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
|
||||
|
||||
if (this.retrycount > 0) {
|
||||
HttpRequestRetryHandler retryHandler = HttpConfigBuilder.getInstance().buildRetryHandler(this.retrycount);
|
||||
clientBuilder.setRetryHandler(retryHandler);
|
||||
}
|
||||
|
||||
if (this.keepaliveDuration > 0) {
|
||||
ConnectionKeepAliveStrategy keepAliveStrategy = HttpConfigBuilder.getInstance().buildKeepAliveStrategy(this.keepaliveDuration);
|
||||
clientBuilder.setKeepAliveStrategy(keepAliveStrategy);
|
||||
}
|
||||
|
||||
if (this.timeout > 0) {
|
||||
RequestConfig requestConfig = HttpConfigBuilder.getInstance().buildRequestConfig(this.timeout);
|
||||
clientBuilder.setDefaultRequestConfig(requestConfig);
|
||||
}
|
||||
|
||||
if (this.maxTotal > 0 && this.maxPerroute > 0) {
|
||||
|
||||
PoolingHttpClientConnectionManager connMgr;
|
||||
if (StringUtils.isNotEmpty(this.sslFile) && StringUtils.isNotEmpty(this.sslFilePwd)) {
|
||||
String path = RestTemplateBuilder.class.getResource("/").getPath();
|
||||
File file = new File(path + this.sslFile);
|
||||
connMgr = HttpConfigBuilder.getInstance().buildP12PoolingHttpClientConnectionManager(maxTotal, this.maxPerroute, file, this.sslFilePwd);
|
||||
}
|
||||
else {
|
||||
connMgr = HttpConfigBuilder.getInstance().buildPoolingHttpClientConnectionManager(maxTotal, this.maxPerroute);
|
||||
}
|
||||
clientBuilder.setConnectionManager(connMgr);
|
||||
}
|
||||
|
||||
// if (StringUtils.isNotEmpty(proxyHost) && proxyPort != null
|
||||
// && StringUtils.isNotEmpty(proxySchema)) {
|
||||
// HttpHost proxy = new HttpHost(proxyHost, proxyPort, proxySchema);
|
||||
// clientBuilder.setProxy(proxy);
|
||||
// }
|
||||
|
||||
CloseableHttpClient httpClient = clientBuilder.build();
|
||||
|
||||
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
requestFactory.setHttpClient(httpClient);
|
||||
|
||||
RestTemplate restTemplate = new RestTemplate(requestFactory);
|
||||
restTemplate.setMessageConverters(getMessageConverters());
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
private List<HttpMessageConverter<?>> getMessageConverters() {
|
||||
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(DEFAULT_CHARSET);
|
||||
stringHttpMessageConverter.setWriteAcceptCharset(false); // 去掉超大accept头
|
||||
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
|
||||
// Jaxb2RootElementHttpMessageConverter xmlHttpMessageConverter = new Jaxb2RootElementHttpMessageConverter();
|
||||
|
||||
MediaType jsonMediaType = MediaType.valueOf("application/json;charset=UTF-8");
|
||||
MediaType textMediaType = MediaType.valueOf("text/html;charset=UTF-8"); // 避免IE出现下载JSON文件的情况
|
||||
// MediaType xmlMediaType = MediaType.valueOf("application/xml;charset=UTF-8");
|
||||
List<MediaType> supportedMediaTypes = Arrays.asList(jsonMediaType, textMediaType);
|
||||
|
||||
fastJsonHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
|
||||
|
||||
List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<>();
|
||||
httpMessageConverters.add(stringHttpMessageConverter);
|
||||
httpMessageConverters.add(fastJsonHttpMessageConverter);
|
||||
// httpMessageConverters.add(xmlHttpMessageConverter);
|
||||
return httpMessageConverters;
|
||||
}
|
||||
|
||||
public int getTimeout() {
|
||||
return timeout;
|
||||
}
|
||||
|
||||
public void setTimeout(int timeout) {
|
||||
this.timeout = timeout;
|
||||
}
|
||||
|
||||
public long getKeepaliveDuration() {
|
||||
return keepaliveDuration;
|
||||
}
|
||||
|
||||
public void setKeepaliveDuration(int keepaliveDuration) {
|
||||
this.keepaliveDuration = keepaliveDuration;
|
||||
}
|
||||
|
||||
public int getRetrycount() {
|
||||
return retrycount;
|
||||
}
|
||||
|
||||
public void setRetrycount(int retrycount) {
|
||||
this.retrycount = retrycount;
|
||||
}
|
||||
|
||||
public int getMaxTotal() {
|
||||
return maxTotal;
|
||||
}
|
||||
|
||||
public void setMaxTotal(int maxTotal) {
|
||||
this.maxTotal = maxTotal;
|
||||
}
|
||||
|
||||
public int getMaxPerroute() {
|
||||
return maxPerroute;
|
||||
}
|
||||
|
||||
public void setMaxPerroute(int maxPerroute) {
|
||||
this.maxPerroute = maxPerroute;
|
||||
}
|
||||
|
||||
public String getSslFile() {
|
||||
return sslFile;
|
||||
}
|
||||
|
||||
public void setSslFile(String sslFile) {
|
||||
this.sslFile = sslFile;
|
||||
}
|
||||
|
||||
public String getSslFilePwd() {
|
||||
return sslFilePwd;
|
||||
}
|
||||
|
||||
public void setSslFilePwd(String sslFilePwd) {
|
||||
this.sslFilePwd = sslFilePwd;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package javautils.http;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.TreeMap;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
/**
|
||||
* url工具类
|
||||
*
|
||||
* @author Mick
|
||||
* @since 2015-9-3
|
||||
*/
|
||||
public class UrlParamUtils {
|
||||
private static final String EMPTY = "";
|
||||
private static final String EQUALS = "=";
|
||||
private static final String DEFAULT_SEPARATOR = "&";
|
||||
|
||||
public static String toUrlParam(Map<String, String> params) {
|
||||
return toUrlParam(params, DEFAULT_SEPARATOR, true);
|
||||
}
|
||||
|
||||
public static String toUrlParam(Map<String, String> params, String separator) {
|
||||
return toUrlParam(params, separator, true);
|
||||
}
|
||||
|
||||
public static String toUrlParam(Map<String, String> params, String separator, boolean ignoreEmpty) {
|
||||
if (params == null || params.isEmpty()) {
|
||||
return EMPTY;
|
||||
}
|
||||
|
||||
StringBuffer url = new StringBuffer();
|
||||
|
||||
Iterator<Entry<String, String>> it = params.entrySet().iterator();
|
||||
while(it.hasNext()) {
|
||||
Entry<String, String> entry = it.next();
|
||||
String value = entry.getValue();
|
||||
boolean valueIsEmpty = isEmpty(value);
|
||||
if (ignoreEmpty && valueIsEmpty) { // 主动忽略空值并且值为空
|
||||
continue;
|
||||
}
|
||||
|
||||
url.append(entry.getKey()).append(EQUALS) .append(value);
|
||||
if (it.hasNext()) {
|
||||
url.append(separator);
|
||||
}
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
|
||||
|
||||
public String buildSignStr(Map<String, Object> params) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
// 将参数以参数名的字典升序排序
|
||||
Map<String, Object> sortParams = new TreeMap<String, Object>(params);
|
||||
// 遍历排序的字典,并拼接"key=value"格式
|
||||
for (Map.Entry<String, Object> entry : sortParams.entrySet()) {
|
||||
if (sb.length()!=0) {
|
||||
sb.append(DEFAULT_SEPARATOR);
|
||||
}
|
||||
sb.append(entry.getKey()).append("=").append(entry.getValue());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
|
||||
public static String toUrlParamWithoutEmpty(Map<String, String> params, String separator,boolean bool) {
|
||||
if (params == null || params.isEmpty()) {
|
||||
return EMPTY;
|
||||
}
|
||||
Map<String, String> sortParams = null;
|
||||
StringBuffer url = new StringBuffer();
|
||||
if(bool){
|
||||
sortParams = new TreeMap<String, String>(params);
|
||||
}else{
|
||||
sortParams = params;
|
||||
}
|
||||
|
||||
Iterator<Entry<String, String>> it = sortParams.entrySet().iterator();
|
||||
while(it.hasNext()) {
|
||||
Entry<String, String> entry = it.next();
|
||||
String value = entry.getValue();
|
||||
if (StringUtils.isEmpty(value)) { // 主动忽略空值并且值为空
|
||||
continue;
|
||||
}
|
||||
|
||||
url.append(entry.getKey()).append(EQUALS) .append(value);
|
||||
if (it.hasNext()) {
|
||||
url.append(separator);
|
||||
}
|
||||
}
|
||||
|
||||
String urlStr = url.toString();
|
||||
if (urlStr.endsWith(separator)) {
|
||||
urlStr = urlStr.substring(0, urlStr.length() - separator.length());
|
||||
}
|
||||
|
||||
return urlStr;
|
||||
}
|
||||
|
||||
public static Map<String, String> fromUrlParam(String url) {
|
||||
Map<String, String> paramsMap = new HashMap<>();
|
||||
|
||||
String[] params = url.split(DEFAULT_SEPARATOR);
|
||||
for (String param : params) {
|
||||
String[] values = param.split(EQUALS);
|
||||
|
||||
if (values == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String key = values.length > 0 ? values[0] : null;
|
||||
String value = values.length > 1 ? values[1] : null;
|
||||
if (key == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
paramsMap.put(key, value);
|
||||
}
|
||||
|
||||
return paramsMap;
|
||||
}
|
||||
|
||||
private static boolean isEmpty(String value) {
|
||||
return value == null || EMPTY.equals(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package javautils.image;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Font;
|
||||
import java.awt.Graphics;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.Random;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
public class ImageCodeUtil {
|
||||
|
||||
static Random r = new Random();
|
||||
|
||||
static int width = 250;
|
||||
static int height = 100;
|
||||
static int line = 80;
|
||||
static int length = 4;
|
||||
static int fontSize = 84;
|
||||
|
||||
public static void generate(String key, HttpServletRequest request, HttpServletResponse response) {
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
|
||||
Graphics g = image.getGraphics();
|
||||
g.fillRect(0, 0, width, height);
|
||||
g.setFont(font());
|
||||
g.setColor(color(110, 133));
|
||||
for (int i = 0; i <= line; i++) {
|
||||
drawLine(g);
|
||||
}
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (int i = 0; i < length; i++) {
|
||||
sb.append(drawString(g, i * 60 + 10, 80));
|
||||
}
|
||||
g.dispose();
|
||||
request.getSession().setAttribute(key, sb.toString());
|
||||
write(image, response);
|
||||
}
|
||||
|
||||
static void write(BufferedImage image, HttpServletResponse response) {
|
||||
response.setContentType("image/png");
|
||||
response.setHeader("Pragma", "No-cache");
|
||||
response.setHeader("Cache-Control", "no-cache");
|
||||
response.setDateHeader("Expire", 0);
|
||||
try {
|
||||
ServletOutputStream out = response.getOutputStream();
|
||||
ImageIO.write(image, "PNG", response.getOutputStream());
|
||||
out.flush();
|
||||
out.close();
|
||||
} catch (Exception e) {}
|
||||
}
|
||||
|
||||
static String drawString(Graphics g, int x, int y) {
|
||||
Random r = new Random();
|
||||
g.setFont(font());
|
||||
int red = r.nextInt(101);
|
||||
int green = r.nextInt(111);
|
||||
int blue = r.nextInt(121);
|
||||
g.setColor(new Color(red, green, blue));
|
||||
//g.translate(r.nextInt(3), r.nextInt(3));
|
||||
String s = string();
|
||||
g.drawString(s, x, y);
|
||||
return s;
|
||||
}
|
||||
|
||||
static void drawLine(Graphics g) {
|
||||
int x = r.nextInt(width);
|
||||
int y = r.nextInt(height);
|
||||
int xl = r.nextInt(13);
|
||||
int yl = r.nextInt(15);
|
||||
g.drawLine(x, y, x + xl, y + yl);
|
||||
}
|
||||
|
||||
static char ch[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
|
||||
|
||||
static Font font() {
|
||||
return new Font("Arial", Font.CENTER_BASELINE, 84);
|
||||
}
|
||||
|
||||
static Color color(int fc, int bc) {
|
||||
if (fc > 255) fc = 255;
|
||||
if (bc > 255) bc = 255;
|
||||
int red = fc + r.nextInt(bc - fc - 16);
|
||||
int green = fc + r.nextInt(bc - fc - 14);
|
||||
int blue = fc + r.nextInt(bc - fc - 18);
|
||||
return new Color(red, green, blue);
|
||||
}
|
||||
|
||||
static String string() {
|
||||
int index = r.nextInt(ch.length);
|
||||
return String.valueOf(ch[index]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package javautils.image;
|
||||
|
||||
import com.google.zxing.BarcodeFormat;
|
||||
import com.google.zxing.EncodeHintType;
|
||||
import com.google.zxing.WriterException;
|
||||
import com.google.zxing.client.j2se.MatrixToImageWriter;
|
||||
import com.google.zxing.common.BitMatrix;
|
||||
import com.google.zxing.qrcode.QRCodeWriter;
|
||||
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Hashtable;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Created by Nick on 2017/1/10.
|
||||
*/
|
||||
public class ImageUtil {
|
||||
/**
|
||||
* 将信息写到二维码中,并进行base64编码
|
||||
*/
|
||||
|
||||
|
||||
|
||||
public static String encodeQR(String signature, int height, int width) {
|
||||
ByteArrayOutputStream outputStream = null;
|
||||
try {
|
||||
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
|
||||
hints.put(EncodeHintType.MARGIN, 1);
|
||||
|
||||
QRCodeWriter writer = new QRCodeWriter();
|
||||
BitMatrix bitMatrix = writer.encode(signature, BarcodeFormat.QR_CODE, height, width, hints);
|
||||
|
||||
outputStream = new ByteArrayOutputStream();
|
||||
MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);
|
||||
|
||||
Base64 encoder = new Base64();
|
||||
return "data:image/jpg;base64," + new String(encoder.encode(outputStream.toByteArray()));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
} finally {
|
||||
if (outputStream != null) {
|
||||
try {
|
||||
outputStream.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static BitMatrix deleteWhite(BitMatrix matrix) {
|
||||
int[] rec = matrix.getEnclosingRectangle();
|
||||
int resWidth = rec[2] + 1;
|
||||
int resHeight = rec[3] + 1;
|
||||
|
||||
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
|
||||
resMatrix.clear();
|
||||
for (int i = 0; i < resWidth; i++) {
|
||||
for (int j = 0; j < resHeight; j++) {
|
||||
if (matrix.get(i + rec[0], j + rec[1]))
|
||||
resMatrix.set(i, j);
|
||||
}
|
||||
}
|
||||
return resMatrix;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
package javautils.image;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.awt.*;
|
||||
import java.awt.geom.AffineTransform;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* Created by Nick on 2016/11/15.
|
||||
*/
|
||||
public class VerifyCodeUtils {
|
||||
//使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了几个容易混淆的字符
|
||||
public static final String VERIFY_CODES = "1234567890";
|
||||
private static Random random = new Random();
|
||||
|
||||
public static String generate(String key, HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
// 设置响应的类型格式为图片格式
|
||||
response.setContentType("image/jpeg");
|
||||
// 禁止图像缓存。
|
||||
response.setHeader("Pragma", "no-cache");
|
||||
response.setHeader("Cache-Control", "no-cache");
|
||||
response.setDateHeader("Expires", 0);
|
||||
|
||||
String code = outputVerifyImage(120, 40, response.getOutputStream(), 6);
|
||||
|
||||
request.getSession(true).setAttribute(key, code);
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用系统默认字符源生成验证码
|
||||
* @param verifySize 验证码长度
|
||||
* @return
|
||||
*/
|
||||
public static String generateVerifyCode(int verifySize){
|
||||
return generateVerifyCode(verifySize, VERIFY_CODES);
|
||||
}
|
||||
/**
|
||||
* 使用指定源生成验证码
|
||||
* @param verifySize 验证码长度
|
||||
* @param sources 验证码字符源
|
||||
* @return
|
||||
*/
|
||||
public static String generateVerifyCode(int verifySize, String sources){
|
||||
if(sources == null || sources.length() == 0){
|
||||
sources = VERIFY_CODES;
|
||||
}
|
||||
int codesLen = sources.length();
|
||||
Random rand = new Random(System.currentTimeMillis());
|
||||
StringBuilder verifyCode = new StringBuilder(verifySize);
|
||||
for(int i = 0; i < verifySize; i++){
|
||||
verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
|
||||
}
|
||||
return verifyCode.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机验证码文件,并返回验证码值
|
||||
* @param w
|
||||
* @param h
|
||||
* @param outputFile
|
||||
* @param verifySize
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
|
||||
String verifyCode = generateVerifyCode(verifySize);
|
||||
outputImage(w, h, outputFile, verifyCode);
|
||||
return verifyCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出随机验证码图片流,并返回验证码值
|
||||
* @param w
|
||||
* @param h
|
||||
* @param os
|
||||
* @param verifySize
|
||||
* @return
|
||||
* @throws IOException
|
||||
*/
|
||||
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
|
||||
String verifyCode = generateVerifyCode(verifySize);
|
||||
outputImage(w, h, os, verifyCode);
|
||||
return verifyCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成指定验证码图像文件
|
||||
* @param w
|
||||
* @param h
|
||||
* @param outputFile
|
||||
* @param code
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
|
||||
if(outputFile == null){
|
||||
return;
|
||||
}
|
||||
File dir = outputFile.getParentFile();
|
||||
if(!dir.exists()){
|
||||
dir.mkdirs();
|
||||
}
|
||||
try{
|
||||
outputFile.createNewFile();
|
||||
FileOutputStream fos = new FileOutputStream(outputFile);
|
||||
outputImage(w, h, fos, code);
|
||||
fos.close();
|
||||
} catch(IOException e){
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出指定验证码图片流
|
||||
* @param w
|
||||
* @param h
|
||||
* @param os
|
||||
* @param code
|
||||
* @throws IOException
|
||||
*/
|
||||
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
|
||||
int verifySize = code.length();
|
||||
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
|
||||
Random rand = new Random();
|
||||
Graphics2D g2 = image.createGraphics();
|
||||
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
|
||||
Color[] colors = new Color[5];
|
||||
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
|
||||
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
|
||||
Color.PINK, Color.YELLOW };
|
||||
float[] fractions = new float[colors.length];
|
||||
for(int i = 0; i < colors.length; i++){
|
||||
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
|
||||
fractions[i] = rand.nextFloat();
|
||||
}
|
||||
Arrays.sort(fractions);
|
||||
|
||||
g2.setColor(Color.GRAY);// 设置边框色
|
||||
g2.fillRect(0, 0, w, h);
|
||||
|
||||
Color c = getRandColor(200, 250);
|
||||
g2.setColor(c);// 设置背景色
|
||||
g2.fillRect(0, 2, w, h-4);
|
||||
|
||||
//绘制干扰线
|
||||
Random random = new Random();
|
||||
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
|
||||
for (int i = 0; i < 20; i++) {
|
||||
int x = random.nextInt(w - 1);
|
||||
int y = random.nextInt(h - 1);
|
||||
int xl = random.nextInt(6) + 1;
|
||||
int yl = random.nextInt(12) + 1;
|
||||
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
|
||||
}
|
||||
|
||||
// 添加噪点
|
||||
float yawpRate = 0.05f;// 噪声率
|
||||
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();
|
||||
image.setRGB(x, y, rgb);
|
||||
}
|
||||
|
||||
shear(g2, w, h, c);// 使图片扭曲
|
||||
|
||||
g2.setColor(getRandColor(100, 160));
|
||||
int fontSize = h-8;
|
||||
Font font = new Font("Algerian", Font.ITALIC, fontSize);
|
||||
g2.setFont(font);
|
||||
char[] chars = code.toCharArray();
|
||||
for(int i = 0; i < verifySize; i++){
|
||||
AffineTransform affine = new AffineTransform();
|
||||
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
|
||||
g2.setTransform(affine);
|
||||
g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
|
||||
}
|
||||
|
||||
g2.dispose();
|
||||
ImageIO.write(image, "jpg", os);
|
||||
}
|
||||
|
||||
private static 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);
|
||||
}
|
||||
|
||||
private static int getRandomIntColor() {
|
||||
int[] rgb = getRandomRgb();
|
||||
int color = 0;
|
||||
for (int c : rgb) {
|
||||
color = color << 8;
|
||||
color = color | c;
|
||||
}
|
||||
return color;
|
||||
}
|
||||
|
||||
private static int[] getRandomRgb() {
|
||||
int[] rgb = new int[3];
|
||||
for (int i = 0; i < 3; i++) {
|
||||
rgb[i] = random.nextInt(255);
|
||||
}
|
||||
return rgb;
|
||||
}
|
||||
|
||||
private static void shear(Graphics g, int w1, int h1, Color color) {
|
||||
shearX(g, w1, h1, color);
|
||||
shearY(g, w1, h1, color);
|
||||
}
|
||||
|
||||
private static 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 static 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
public static void main(String[] args) throws IOException{
|
||||
File dir = new File("F:/verifies");
|
||||
int w = 200, h = 80;
|
||||
for(int i = 0; i < 50; i++){
|
||||
String verifyCode = generateVerifyCode(4);
|
||||
File file = new File(dir, verifyCode + ".jpg");
|
||||
outputImage(w, h, file, verifyCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package javautils.ip;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
public class IpUtil {
|
||||
|
||||
public static void main(String[] args){
|
||||
IpUtil.load("D:\\17monipdb.dat");
|
||||
|
||||
System.out.println(Arrays.toString(IpUtil.find("192.168.100.55")));
|
||||
//System.out.println(Arrays.toString(IP.find("255.255.255.255")));
|
||||
}
|
||||
|
||||
public static boolean enableFileWatch = false;
|
||||
|
||||
private static int offset;
|
||||
private static int[] index = new int[256];
|
||||
private static ByteBuffer dataBuffer;
|
||||
private static ByteBuffer indexBuffer;
|
||||
private static Long lastModifyTime = 0L;
|
||||
private static File ipFile ;
|
||||
private static ReentrantLock lock = new ReentrantLock();
|
||||
|
||||
public static void load(String filename) {
|
||||
ipFile = new File(filename);
|
||||
load();
|
||||
if (enableFileWatch) {
|
||||
watch();
|
||||
}
|
||||
}
|
||||
|
||||
public static String[] find(String ip) {
|
||||
int ip_prefix_value = new Integer(ip.substring(0, ip.indexOf(".")));
|
||||
long ip2long_value = ip2long(ip);
|
||||
int start = index[ip_prefix_value];
|
||||
int max_comp_len = offset - 1028;
|
||||
long index_offset = -1;
|
||||
int index_length = -1;
|
||||
byte b = 0;
|
||||
for (start = start * 8 + 1024; start < max_comp_len; start += 8) {
|
||||
if (int2long(indexBuffer.getInt(start)) >= ip2long_value) {
|
||||
index_offset = bytesToLong(b, indexBuffer.get(start + 6), indexBuffer.get(start + 5), indexBuffer.get(start + 4));
|
||||
index_length = 0xFF & indexBuffer.get(start + 7);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
byte[] areaBytes;
|
||||
lock.lock();
|
||||
try {
|
||||
dataBuffer.position(offset + (int) index_offset - 1024);
|
||||
areaBytes = new byte[index_length];
|
||||
dataBuffer.get(areaBytes, 0, index_length);
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
return new String(areaBytes).split("\t");
|
||||
}
|
||||
|
||||
private static void watch() {
|
||||
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
long time = ipFile.lastModified();
|
||||
if (time > lastModifyTime) {
|
||||
lastModifyTime = time;
|
||||
load();
|
||||
}
|
||||
}
|
||||
}, 1000L, 5000L, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private static void load() {
|
||||
lastModifyTime = ipFile.lastModified();
|
||||
FileInputStream fin = null;
|
||||
lock.lock();
|
||||
try {
|
||||
dataBuffer = ByteBuffer.allocate(Long.valueOf(ipFile.length()).intValue());
|
||||
fin = new FileInputStream(ipFile);
|
||||
int readBytesLength;
|
||||
byte[] chunk = new byte[4096];
|
||||
while (fin.available() > 0) {
|
||||
readBytesLength = fin.read(chunk);
|
||||
dataBuffer.put(chunk, 0, readBytesLength);
|
||||
}
|
||||
dataBuffer.position(0);
|
||||
int indexLength = dataBuffer.getInt();
|
||||
byte[] indexBytes = new byte[indexLength];
|
||||
dataBuffer.get(indexBytes, 0, indexLength - 4);
|
||||
indexBuffer = ByteBuffer.wrap(indexBytes);
|
||||
indexBuffer.order(ByteOrder.LITTLE_ENDIAN);
|
||||
offset = indexLength;
|
||||
|
||||
int loop = 0;
|
||||
while (loop++ < 256) {
|
||||
index[loop - 1] = indexBuffer.getInt();
|
||||
}
|
||||
indexBuffer.order(ByteOrder.BIG_ENDIAN);
|
||||
} catch (IOException ioe) {
|
||||
|
||||
} finally {
|
||||
try {
|
||||
if (fin != null) {
|
||||
fin.close();
|
||||
}
|
||||
} catch (IOException e){}
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
private static long bytesToLong(byte a, byte b, byte c, byte d) {
|
||||
return int2long((((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff)));
|
||||
}
|
||||
|
||||
private static int str2Ip(String ip) {
|
||||
String[] ss = ip.split("\\.");
|
||||
int a, b, c, d;
|
||||
a = Integer.parseInt(ss[0]);
|
||||
b = Integer.parseInt(ss[1]);
|
||||
c = Integer.parseInt(ss[2]);
|
||||
d = Integer.parseInt(ss[3]);
|
||||
return (a << 24) | (b << 16) | (c << 8) | d;
|
||||
}
|
||||
|
||||
private static long ip2long(String ip) {
|
||||
return int2long(str2Ip(ip));
|
||||
}
|
||||
|
||||
private static long int2long(int i) {
|
||||
long l = i & 0x7fffffffL;
|
||||
if (i < 0) {
|
||||
l |= 0x080000000L;
|
||||
}
|
||||
return l;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package javautils.jdbc;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 分页类
|
||||
* @author root
|
||||
*
|
||||
*/
|
||||
public class PageList {
|
||||
|
||||
private List<?> list;
|
||||
private int count;
|
||||
|
||||
public PageList() {
|
||||
this.list = new ArrayList<>();
|
||||
this.count = 0;
|
||||
}
|
||||
|
||||
public PageList(List<?> list, int count) {
|
||||
this.list = list;
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
public List<?> getList() {
|
||||
return list;
|
||||
}
|
||||
|
||||
public void setList(List<?> list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
public int getCount() {
|
||||
return count;
|
||||
}
|
||||
|
||||
public void setCount(int count) {
|
||||
this.count = count;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package javautils.jdbc.helper;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import net.sf.json.JSONArray;
|
||||
import net.sf.json.JSONObject;
|
||||
|
||||
public class JDBCHelper {
|
||||
|
||||
public final static String MYSQL = "com.mysql.jdbc.Driver";
|
||||
|
||||
public static Connection openConnection(String url, String username,
|
||||
String password, String type) {
|
||||
Connection conn = null;
|
||||
try {
|
||||
Class.forName(type);
|
||||
conn = DriverManager.getConnection(url, username, password);
|
||||
} catch (Exception e) {}
|
||||
return conn;
|
||||
}
|
||||
|
||||
public static boolean executeUpdate(String sql, Connection conn) {
|
||||
boolean flag = false;
|
||||
if (conn != null) {
|
||||
PreparedStatement pst = null;
|
||||
try {
|
||||
pst = conn.prepareStatement(sql);
|
||||
int count = pst.executeUpdate();
|
||||
flag = count > 0 ? true : false;
|
||||
} catch (Exception e) {
|
||||
} finally {
|
||||
try {
|
||||
if (pst != null) pst.close();
|
||||
if (conn != null) conn.close();
|
||||
} catch (SQLException e) {}
|
||||
}
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
public static JSONArray executeQuery(String sql, Connection conn) {
|
||||
JSONArray list = null;
|
||||
if (conn != null) {
|
||||
PreparedStatement pst = null;
|
||||
try {
|
||||
pst = conn.prepareStatement(sql);
|
||||
ResultSet rs = pst.executeQuery();
|
||||
list = toJsonArray(rs);
|
||||
} catch (Exception e) {} finally {
|
||||
try {
|
||||
if (pst != null) pst.close();
|
||||
if (conn != null) conn.close();
|
||||
} catch (SQLException e) {}
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public static JSONArray toJsonArray(ResultSet rs) throws Exception {
|
||||
JSONArray list = new JSONArray();
|
||||
if (rs != null) {
|
||||
ResultSetMetaData metaData = rs.getMetaData();
|
||||
int columnCount = metaData.getColumnCount();
|
||||
while (rs.next()) {
|
||||
JSONObject obj = new JSONObject();
|
||||
for (int i = 0; i < columnCount; i++) {
|
||||
String columnName = metaData.getColumnLabel(i + 1);
|
||||
String value = rs.getString(columnName);
|
||||
obj.put(columnName, value);
|
||||
}
|
||||
list.add(obj);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* java:comp/env/jdbc/books
|
||||
* @param jndi
|
||||
* @return
|
||||
*/
|
||||
public static Connection openConnection(String jndi) {
|
||||
Connection conn = null;
|
||||
try {
|
||||
Context context = new InitialContext();
|
||||
DataSource source = (DataSource) context.lookup(jndi);
|
||||
conn = source.getConnection();
|
||||
} catch (Exception e) {}
|
||||
return conn;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String url = "jdbc:mysql://192.168.1.111:3306/test?useUnicode=true&characterEncoding=utf-8";
|
||||
String username = "root";
|
||||
String password = "root";
|
||||
Connection conn = JDBCHelper.openConnection(url, username, password, JDBCHelper.MYSQL);
|
||||
String sql = "select * from user";
|
||||
JDBCHelper.executeQuery(sql, conn);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,690 @@
|
||||
package javautils.jdbc.hibernate;
|
||||
|
||||
import javautils.jdbc.PageList;
|
||||
import javautils.jdbc.util.BatchSQLUtil;
|
||||
import org.apache.commons.collections.CollectionUtils;
|
||||
import org.hibernate.*;
|
||||
import org.hibernate.criterion.Criterion;
|
||||
import org.hibernate.criterion.Order;
|
||||
import org.hibernate.criterion.Projection;
|
||||
import org.hibernate.criterion.Projections;
|
||||
import org.hibernate.jdbc.Work;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
@SuppressWarnings("unchecked")
|
||||
public class HibernateSuperDao<T> {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(HibernateSuperDao.class);
|
||||
|
||||
@Autowired
|
||||
@Qualifier("sessionFactoryWrite")
|
||||
private SessionFactory sessionFactory;
|
||||
|
||||
public Session getCurrentSession() {
|
||||
return sessionFactory.getCurrentSession();
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存
|
||||
* @param entity
|
||||
* @return
|
||||
*/
|
||||
@Transactional
|
||||
public boolean save(final Object entity) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
getCurrentSession().save(entity);
|
||||
flag = true;
|
||||
} catch (Exception e) {
|
||||
logger.error("保存实体类异常", e);
|
||||
throw e;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新
|
||||
* @param entity
|
||||
* @return
|
||||
*/
|
||||
@Transactional
|
||||
public boolean update(final Object entity) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
getCurrentSession().update(entity);
|
||||
flag = true;
|
||||
} catch (Exception e) {
|
||||
logger.error("更新实体类异常", e);
|
||||
throw e;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新
|
||||
* @param hql
|
||||
* @param values
|
||||
* @return
|
||||
*/
|
||||
@Transactional
|
||||
public boolean update(final String hql, final Object[] values) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
query.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
int result = query.executeUpdate();
|
||||
flag = result > 0 ? true : false;
|
||||
} catch (Exception e) {
|
||||
logger.error("更新实体类异常", e);
|
||||
throw e;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除
|
||||
* @param entity
|
||||
* @return
|
||||
*/
|
||||
public boolean delete(final Object entity) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
getCurrentSession().delete(entity);
|
||||
flag = true;
|
||||
} catch (Exception e) {
|
||||
logger.error("删除实体类异常", e);
|
||||
throw e;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除
|
||||
* @param hql
|
||||
* @param values
|
||||
* @return
|
||||
*/
|
||||
@Transactional
|
||||
public boolean delete(final String hql, final Object[] values) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
query.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
int result = query.executeUpdate();
|
||||
flag = result > 0 ? true : false;
|
||||
} catch (Exception e) {
|
||||
logger.error("删除实体类异常", e);
|
||||
throw e;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询
|
||||
* @param hql
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> list(final String hql) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询
|
||||
* @param hql
|
||||
* @param start
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> list(final String hql, final int start, final int limit) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
if(start >= 0 && limit > 0) {
|
||||
query.setFirstResult(start);
|
||||
query.setMaxResults(limit);
|
||||
}
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 唯一结果查询
|
||||
* @param hql
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Object unique(final String hql) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
return query.uniqueResult();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 唯一结果查询
|
||||
* @param hql
|
||||
* @param values
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Object unique(final String hql, final Object[] values) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
query.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
return query.uniqueResult();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询
|
||||
* @param hql
|
||||
* @param values
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> list(final String hql, final Object[] values) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
query.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 唯一结果查询
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Object uniqueSqlWithParams(final String sql, final Map<String, Object> params) {
|
||||
try {
|
||||
Query query = getCurrentSession().createSQLQuery(sql);
|
||||
for (String key : params.keySet()) {
|
||||
query.setParameter(key, params.get(key));
|
||||
}
|
||||
return query.uniqueResult();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<?> listBySql(final String sql, final Map<String, Object> params) {
|
||||
try {
|
||||
Query query = getCurrentSession().createSQLQuery(sql);
|
||||
for (String key : params.keySet()) {
|
||||
query.setParameter(key, params.get(key));
|
||||
}
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<?> listBySql(final String sql, final Map<String, Object> params, final int start, final int limit) {
|
||||
try {
|
||||
Query query = getCurrentSession().createSQLQuery(sql);
|
||||
for (String key : params.keySet()) {
|
||||
query.setParameter(key, params.get(key));
|
||||
}
|
||||
if(start >= 0 && limit > 0) {
|
||||
query.setFirstResult(start);
|
||||
query.setMaxResults(limit);
|
||||
}
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询
|
||||
* @param hql
|
||||
* @param values
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<?> listObject(final String hql, final Object[] values) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
query.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询
|
||||
* @param hql
|
||||
* @param values
|
||||
* @param start
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> list(final String hql, final Object[] values, final int start, final int limit) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
query.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
if(start >= 0 && limit > 0) {
|
||||
query.setFirstResult(start);
|
||||
query.setMaxResults(limit);
|
||||
}
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL查询
|
||||
* @param sql
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<?> findWithSql(final String sql) {
|
||||
try {
|
||||
SQLQuery query = getCurrentSession().createSQLQuery(sql);
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL查询
|
||||
* @param sql
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Object uniqueWithSqlCount(final String sql) {
|
||||
try {
|
||||
SQLQuery query = getCurrentSession().createSQLQuery(sql);
|
||||
return query.uniqueResult();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
* @param querySql
|
||||
* @param countSql
|
||||
* @param start
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public PageList findPageList(final String querySql, final String countSql, final int start, final int limit) {
|
||||
try {
|
||||
PageList pList = new PageList();
|
||||
// 查询总数
|
||||
SQLQuery countQuery = getCurrentSession().createSQLQuery(countSql);
|
||||
Number result = (Number) countQuery.uniqueResult();
|
||||
int count = result.intValue();
|
||||
pList.setCount(count);
|
||||
if (count > 0) {
|
||||
// 查询集合
|
||||
SQLQuery listQuery = getCurrentSession().createSQLQuery(querySql);
|
||||
if(start >= 0 && limit > 0) {
|
||||
listQuery.setFirstResult(start);
|
||||
listQuery.setMaxResults(limit);
|
||||
}
|
||||
List<T> list = listQuery.list();
|
||||
pList.setList(list);
|
||||
}
|
||||
else {
|
||||
pList.setList(new ArrayList<>());
|
||||
}
|
||||
return pList;
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public PageList findPageList(final String queryHql, final String countHql, final Object[] values, final int start, final int limit) {
|
||||
try {
|
||||
PageList pList = new PageList();
|
||||
// 查询总数
|
||||
Query countQuery = getCurrentSession().createQuery(countHql);
|
||||
if (values != null && values.length > 0) {
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
countQuery.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
}
|
||||
|
||||
Number result = (Number) countQuery.uniqueResult();
|
||||
int count = result.intValue();
|
||||
pList.setCount(count);
|
||||
if (count > 0) {
|
||||
// 查询集合
|
||||
Query listQuery = getCurrentSession().createQuery(queryHql);
|
||||
|
||||
if (values != null && values.length > 0) {
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
listQuery.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if(start >= 0 && limit > 0) {
|
||||
listQuery.setFirstResult(start);
|
||||
listQuery.setMaxResults(limit);
|
||||
}
|
||||
List<T> list = listQuery.list();
|
||||
pList.setList(list);
|
||||
}
|
||||
|
||||
return pList;
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public PageList findPageList(final String sql, Map<String, Object> params, final int start, final int limit) {
|
||||
try {
|
||||
PageList pList = new PageList();
|
||||
// 查询总数
|
||||
String countSql = "select count(*) from (" + sql + ") _t1";
|
||||
SQLQuery countQuery = getCurrentSession().createSQLQuery(countSql);
|
||||
if (params != null && !params.isEmpty()) {
|
||||
for (Map.Entry<String, Object> entry : params.entrySet()) {
|
||||
countQuery.setParameter(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
Number result = (Number) countQuery.uniqueResult();
|
||||
int count = result.intValue();
|
||||
pList.setCount(count);
|
||||
if (count > 0) {
|
||||
// 查询集合
|
||||
SQLQuery listQuery = getCurrentSession().createSQLQuery(sql);
|
||||
|
||||
if (params != null && !params.isEmpty()) {
|
||||
for (Map.Entry<String, Object> entry : params.entrySet()) {
|
||||
listQuery.setParameter(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
if(start >= 0 && limit > 0) {
|
||||
listQuery.setFirstResult(start);
|
||||
listQuery.setMaxResults(limit);
|
||||
}
|
||||
List<T> list = listQuery.list();
|
||||
pList.setList(list);
|
||||
}
|
||||
return pList;
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
* @param clazz
|
||||
* @param criterions
|
||||
* @param orders
|
||||
* @param start
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public PageList findPageList(final Class<T> clazz, String propertyName, final List<Criterion> criterions, final List<Order> orders, final int start, final int limit) {
|
||||
try {
|
||||
PageList pList = new PageList();
|
||||
Criteria criteria = getCurrentSession().createCriteria(clazz);
|
||||
for (Criterion criterion : criterions) {
|
||||
criteria.add(criterion);
|
||||
}
|
||||
for (Order order : orders) {
|
||||
criteria.addOrder(order);
|
||||
}
|
||||
// 查询总数
|
||||
criteria.setProjection(Projections.count(propertyName));
|
||||
Number result = (Number) criteria.uniqueResult();
|
||||
int count = result.intValue();
|
||||
pList.setCount(count);
|
||||
criteria.setProjection(null);
|
||||
// 查询集合
|
||||
if(start >= 0 && limit > 0) {
|
||||
criteria.setFirstResult(start);
|
||||
criteria.setMaxResults(limit);
|
||||
}
|
||||
List<T> list = criteria.list();
|
||||
pList.setList(list);
|
||||
return pList;
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public PageList findPageList(final Class<T> clazz, final List<Criterion> criterions, final List<Order> orders, final int start, final int limit) {
|
||||
try {
|
||||
PageList pList = new PageList();
|
||||
Criteria criteria = getCurrentSession().createCriteria(clazz);
|
||||
for (Criterion criterion : criterions) {
|
||||
criteria.add(criterion);
|
||||
}
|
||||
for (Order order : orders) {
|
||||
criteria.addOrder(order);
|
||||
}
|
||||
// 查询总数
|
||||
criteria.setProjection(Projections.rowCount());
|
||||
Number result = (Number) criteria.uniqueResult();
|
||||
int count = result.intValue();
|
||||
pList.setCount(count);
|
||||
criteria.setProjection(null);
|
||||
// 查询集合
|
||||
if(start >= 0 && limit > 0) {
|
||||
criteria.setFirstResult(start);
|
||||
criteria.setMaxResults(limit);
|
||||
}
|
||||
List<T> list = criteria.list();
|
||||
pList.setList(list);
|
||||
return pList;
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Criteria查询
|
||||
* @param clazz
|
||||
* @param criterions
|
||||
* @param orders
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> findByCriteria(final Class<T> clazz, final List<Criterion> criterions, final List<Order> orders) {
|
||||
try {
|
||||
Criteria criteria = getCurrentSession().createCriteria(clazz);
|
||||
for (Criterion criterion : criterions) {
|
||||
criteria.add(criterion);
|
||||
}
|
||||
if (CollectionUtils.isNotEmpty(orders)) {
|
||||
for (Order order : orders) {
|
||||
criteria.addOrder(order);
|
||||
}
|
||||
}
|
||||
return criteria.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Criteria查询
|
||||
* @param clazz
|
||||
* @param criterions
|
||||
* @param orders
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> findByCriteria(final Class<T> clazz, final List<Criterion> criterions, final List<Order> orders, final int start, final int limit) {
|
||||
try {
|
||||
Criteria criteria = getCurrentSession().createCriteria(clazz);
|
||||
for (Criterion criterion : criterions) {
|
||||
criteria.add(criterion);
|
||||
}
|
||||
for (Order order : orders) {
|
||||
criteria.addOrder(order);
|
||||
}
|
||||
if(start >= 0 && limit > 0) {
|
||||
criteria.setFirstResult(start);
|
||||
criteria.setMaxResults(limit);
|
||||
}
|
||||
return criteria.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Criteria查询
|
||||
* @param clazz
|
||||
* @param criterions
|
||||
* @param orders
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<?> findByCriteria(final Class<T> clazz, final List<Criterion> criterions, final List<Order> orders, final Projection projection) {
|
||||
try {
|
||||
Criteria criteria = getCurrentSession().createCriteria(clazz);
|
||||
for (Criterion criterion : criterions) {
|
||||
criteria.add(criterion);
|
||||
}
|
||||
for (Order order : orders) {
|
||||
criteria.addOrder(order);
|
||||
}
|
||||
criteria.setProjection(projection);
|
||||
return criteria.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Criteria查询
|
||||
* @param clazz
|
||||
* @param criterions
|
||||
* @param orders
|
||||
* @param projection
|
||||
* @param start
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<?> findByCriteria(final Class<T> clazz, final List<Criterion> criterions, final List<Order> orders, final Projection projection, final int start, final int limit) {
|
||||
try {
|
||||
Criteria criteria = getCurrentSession().createCriteria(clazz);
|
||||
for (Criterion criterion : criterions) {
|
||||
criteria.add(criterion);
|
||||
}
|
||||
for (Order order : orders) {
|
||||
criteria.addOrder(order);
|
||||
}
|
||||
criteria.setProjection(projection);
|
||||
if(start >= 0 && limit > 0) {
|
||||
criteria.setFirstResult(start);
|
||||
criteria.setMaxResults(limit);
|
||||
}
|
||||
return criteria.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public boolean doWork(final String sql, final List<Object[]> params) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
getCurrentSession().doWork(new Work() {
|
||||
@Override
|
||||
public void execute(Connection connection) throws SQLException {
|
||||
BatchSQLUtil sqlUtil = new BatchSQLUtil(connection, sql);
|
||||
for (Object[] param : params) {
|
||||
sqlUtil.addCount(param);
|
||||
}
|
||||
sqlUtil.commit();
|
||||
}
|
||||
});
|
||||
flag = true;
|
||||
} catch (Exception e) {
|
||||
logger.error("doWork出错", e);
|
||||
throw e;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,792 @@
|
||||
package javautils.jdbc.hibernate;
|
||||
|
||||
import javautils.jdbc.PageList;
|
||||
import javautils.jdbc.util.BatchSQLUtil;
|
||||
import org.apache.commons.collections.CollectionUtils;
|
||||
import org.hibernate.*;
|
||||
import org.hibernate.criterion.Criterion;
|
||||
import org.hibernate.criterion.Order;
|
||||
import org.hibernate.criterion.Projection;
|
||||
import org.hibernate.criterion.Projections;
|
||||
import org.hibernate.jdbc.Work;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@Component
|
||||
@SuppressWarnings("unchecked")
|
||||
public class HibernateSuperReadDao<T> {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(HibernateSuperReadDao.class);
|
||||
|
||||
@Autowired
|
||||
@Qualifier("sessionFactoryRead")
|
||||
private SessionFactory sessionFactory;
|
||||
|
||||
public Session getCurrentSession() {
|
||||
return sessionFactory.getCurrentSession();
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存
|
||||
* @param entity
|
||||
* @return
|
||||
*/
|
||||
@Transactional
|
||||
public boolean save(final Object entity) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
getCurrentSession().save(entity);
|
||||
flag = true;
|
||||
} catch (Exception e) {
|
||||
logger.error("保存实体类异常", e);
|
||||
throw e;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新
|
||||
* @param entity
|
||||
* @return
|
||||
*/
|
||||
@Transactional
|
||||
public boolean update(final Object entity) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
getCurrentSession().update(entity);
|
||||
flag = true;
|
||||
} catch (Exception e) {
|
||||
logger.error("更新实体类异常", e);
|
||||
throw e;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新
|
||||
* @param hql
|
||||
* @param values
|
||||
* @return
|
||||
*/
|
||||
@Transactional
|
||||
public boolean update(final String hql, final Object[] values) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
query.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
int result = query.executeUpdate();
|
||||
flag = result > 0 ? true : false;
|
||||
} catch (Exception e) {
|
||||
logger.error("更新实体类异常", e);
|
||||
throw e;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除
|
||||
* @param entity
|
||||
* @return
|
||||
*/
|
||||
public boolean delete(final Object entity) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
getCurrentSession().delete(entity);
|
||||
flag = true;
|
||||
} catch (Exception e) {
|
||||
logger.error("删除实体类异常", e);
|
||||
throw e;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除
|
||||
* @param hql
|
||||
* @param values
|
||||
* @return
|
||||
*/
|
||||
@Transactional
|
||||
public boolean delete(final String hql, final Object[] values) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
query.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
int result = query.executeUpdate();
|
||||
flag = result > 0 ? true : false;
|
||||
} catch (Exception e) {
|
||||
logger.error("删除实体类异常", e);
|
||||
throw e;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询
|
||||
* @param hql
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> list(final String hql) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询
|
||||
* @param hql
|
||||
* @param start
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> list(final String hql, final int start, final int limit) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
if(start >= 0 && limit > 0) {
|
||||
query.setFirstResult(start);
|
||||
query.setMaxResults(limit);
|
||||
}
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 唯一结果查询
|
||||
* @param hql
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Object unique(final String hql) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
return query.uniqueResult();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 唯一结果查询
|
||||
* @param hql
|
||||
* @param values
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Object unique(final String hql, final Object[] values) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
query.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
return query.uniqueResult();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询
|
||||
* @param hql
|
||||
* @param values
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> list(final String hql, final Object[] values) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
query.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 唯一结果查询
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Object uniqueSqlWithParams(final String sql, final Map<String, Object> params) {
|
||||
try {
|
||||
Query query = getCurrentSession().createSQLQuery(sql);
|
||||
for (String key : params.keySet()) {
|
||||
query.setParameter(key, params.get(key));
|
||||
}
|
||||
return query.uniqueResult();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<?> listBySql(final String sql, final Map<String, Object> params) {
|
||||
try {
|
||||
Query query = getCurrentSession().createSQLQuery(sql);
|
||||
for (String key : params.keySet()) {
|
||||
query.setParameter(key, params.get(key));
|
||||
}
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<?> listBySql(final String sql, final Map<String, Object> params, final int start, final int limit) {
|
||||
try {
|
||||
Query query = getCurrentSession().createSQLQuery(sql);
|
||||
for (String key : params.keySet()) {
|
||||
query.setParameter(key, params.get(key));
|
||||
}
|
||||
if(start >= 0 && limit > 0) {
|
||||
query.setFirstResult(start);
|
||||
query.setMaxResults(limit);
|
||||
}
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询
|
||||
* @param hql
|
||||
* @param values
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<?> listObject(final String hql, final Object[] values) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
query.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询
|
||||
* @param hql
|
||||
* @param values
|
||||
* @param start
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> list(final String hql, final Object[] values, final int start, final int limit) {
|
||||
try {
|
||||
Query query = getCurrentSession().createQuery(hql);
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
query.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
if(start >= 0 && limit > 0) {
|
||||
query.setFirstResult(start);
|
||||
query.setMaxResults(limit);
|
||||
}
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL查询
|
||||
* @param sql
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<?> findWithSql(final String sql) {
|
||||
try {
|
||||
SQLQuery query = getCurrentSession().createSQLQuery(sql);
|
||||
return query.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL查询
|
||||
* @param sql
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public Object uniqueWithSqlCount(final String sql) {
|
||||
try {
|
||||
SQLQuery query = getCurrentSession().createSQLQuery(sql);
|
||||
return query.uniqueResult();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
* @param querySql
|
||||
* @param countSql
|
||||
* @param start
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public PageList findPageList(final String querySql, final String countSql, final int start, final int limit) {
|
||||
try {
|
||||
PageList pList = new PageList();
|
||||
// 查询总数
|
||||
SQLQuery countQuery = getCurrentSession().createSQLQuery(countSql);
|
||||
Number result = (Number) countQuery.uniqueResult();
|
||||
int count = result.intValue();
|
||||
pList.setCount(count);
|
||||
if (count > 0) {
|
||||
// 查询集合
|
||||
SQLQuery listQuery = getCurrentSession().createSQLQuery(querySql);
|
||||
if(start >= 0 && limit > 0) {
|
||||
listQuery.setFirstResult(start);
|
||||
listQuery.setMaxResults(limit);
|
||||
}
|
||||
List<T> list = listQuery.list();
|
||||
pList.setList(list);
|
||||
}
|
||||
else {
|
||||
pList.setList(new ArrayList<>());
|
||||
}
|
||||
return pList;
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public PageList findPageList(final String queryHql, final String countHql, final Object[] values, final int start, final int limit) {
|
||||
try {
|
||||
PageList pList = new PageList();
|
||||
// 查询总数
|
||||
Query countQuery = getCurrentSession().createQuery(countHql);
|
||||
if (values != null && values.length > 0) {
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
countQuery.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
}
|
||||
|
||||
Number result = (Number) countQuery.uniqueResult();
|
||||
int count = result.intValue();
|
||||
pList.setCount(count);
|
||||
if (count > 0) {
|
||||
// 查询集合
|
||||
Query listQuery = getCurrentSession().createQuery(queryHql);
|
||||
|
||||
if (values != null && values.length > 0) {
|
||||
for (int i = 0; i < values.length; i++) {
|
||||
listQuery.setParameter(String.valueOf(i), values[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if(start >= 0 && limit > 0) {
|
||||
listQuery.setFirstResult(start);
|
||||
listQuery.setMaxResults(limit);
|
||||
}
|
||||
List<T> list = listQuery.list();
|
||||
pList.setList(list);
|
||||
}
|
||||
|
||||
return pList;
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public PageList findPageListByHQL(final String queryHql, final String countHql, final Map<String, Object> params, final int start, final int limit) {
|
||||
try {
|
||||
PageList pList = new PageList();
|
||||
// 查询总数
|
||||
Query countQuery = getCurrentSession().createQuery(countHql);
|
||||
if (params != null && params.size() > 0) {
|
||||
Set<String> paramKeys = params.keySet();
|
||||
for (String paramKey : paramKeys) {
|
||||
countQuery.setParameter(paramKey, params.get(paramKey));
|
||||
}
|
||||
}
|
||||
|
||||
Number result = (Number) countQuery.uniqueResult();
|
||||
int count = result.intValue();
|
||||
pList.setCount(count);
|
||||
if (count > 0) {
|
||||
// 查询集合
|
||||
Query listQuery = getCurrentSession().createQuery(queryHql);
|
||||
|
||||
if (params != null && params.size() > 0) {
|
||||
Set<String> paramKeys = params.keySet();
|
||||
for (String paramKey : paramKeys) {
|
||||
listQuery.setParameter(paramKey, params.get(paramKey));
|
||||
}
|
||||
}
|
||||
|
||||
if(start >= 0 && limit > 0) {
|
||||
listQuery.setFirstResult(start);
|
||||
listQuery.setMaxResults(limit);
|
||||
}
|
||||
List<T> list = listQuery.list();
|
||||
pList.setList(list);
|
||||
}
|
||||
|
||||
return pList;
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public PageList findPageList(final String sql, Map<String, Object> params, final int start, final int limit) {
|
||||
try {
|
||||
PageList pList = new PageList();
|
||||
// 查询总数
|
||||
String countSql = "select count(*) from (" + sql + ") _t1";
|
||||
SQLQuery countQuery = getCurrentSession().createSQLQuery(countSql);
|
||||
if (params != null && !params.isEmpty()) {
|
||||
for (Map.Entry<String, Object> entry : params.entrySet()) {
|
||||
countQuery.setParameter(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
Number result = (Number) countQuery.uniqueResult();
|
||||
int count = result.intValue();
|
||||
pList.setCount(count);
|
||||
if (count > 0) {
|
||||
// 查询集合
|
||||
SQLQuery listQuery = getCurrentSession().createSQLQuery(sql);
|
||||
|
||||
if (params != null && !params.isEmpty()) {
|
||||
for (Map.Entry<String, Object> entry : params.entrySet()) {
|
||||
listQuery.setParameter(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
if(start >= 0 && limit > 0) {
|
||||
listQuery.setFirstResult(start);
|
||||
listQuery.setMaxResults(limit);
|
||||
}
|
||||
List<T> list = listQuery.list();
|
||||
pList.setList(list);
|
||||
}
|
||||
return pList;
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public PageList findPageList(final String countSql, final String querySql, Map<String, Object> params, final int start, final int limit) {
|
||||
try {
|
||||
PageList pList = new PageList();
|
||||
// 查询总数
|
||||
SQLQuery countQuery = getCurrentSession().createSQLQuery(countSql);
|
||||
if (params != null && !params.isEmpty()) {
|
||||
for (Map.Entry<String, Object> entry : params.entrySet()) {
|
||||
countQuery.setParameter(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
Number result = (Number) countQuery.uniqueResult();
|
||||
int count = result.intValue();
|
||||
pList.setCount(count);
|
||||
if (count > 0) {
|
||||
// 查询集合
|
||||
SQLQuery listQuery = getCurrentSession().createSQLQuery(querySql);
|
||||
|
||||
if (params != null && !params.isEmpty()) {
|
||||
for (Map.Entry<String, Object> entry : params.entrySet()) {
|
||||
listQuery.setParameter(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
if(start >= 0 && limit > 0) {
|
||||
listQuery.setFirstResult(start);
|
||||
listQuery.setMaxResults(limit);
|
||||
}
|
||||
List<T> list = listQuery.list();
|
||||
pList.setList(list);
|
||||
}
|
||||
return pList;
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
* @param clazz
|
||||
* @param criterions
|
||||
* @param orders
|
||||
* @param start
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public PageList findPageList(final Class<T> clazz, String propertyName, final List<Criterion> criterions, final List<Order> orders, final int start, final int limit) {
|
||||
try {
|
||||
PageList pList = new PageList();
|
||||
Criteria criteria = getCurrentSession().createCriteria(clazz);
|
||||
if (CollectionUtils.isNotEmpty(criterions)) {
|
||||
for (Criterion criterion : criterions) {
|
||||
criteria.add(criterion);
|
||||
}
|
||||
}
|
||||
if (CollectionUtils.isNotEmpty(orders)) {
|
||||
for (Order order : orders) {
|
||||
criteria.addOrder(order);
|
||||
}
|
||||
}
|
||||
|
||||
// 查询总数
|
||||
criteria.setProjection(Projections.count(propertyName));
|
||||
Number result = (Number) criteria.uniqueResult();
|
||||
int count = result.intValue();
|
||||
pList.setCount(count);
|
||||
criteria.setProjection(null);
|
||||
// 查询集合
|
||||
if(start >= 0 && limit > 0) {
|
||||
criteria.setFirstResult(start);
|
||||
criteria.setMaxResults(limit);
|
||||
}
|
||||
List<T> list = criteria.list();
|
||||
pList.setList(list);
|
||||
return pList;
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public PageList findPageList(final Class<T> clazz, final List<Criterion> criterions, final List<Order> orders, final int start, final int limit) {
|
||||
try {
|
||||
PageList pList = new PageList();
|
||||
Criteria criteria = getCurrentSession().createCriteria(clazz);
|
||||
if (CollectionUtils.isNotEmpty(criterions)) {
|
||||
for (Criterion criterion : criterions) {
|
||||
criteria.add(criterion);
|
||||
}
|
||||
}
|
||||
if (CollectionUtils.isNotEmpty(orders)) {
|
||||
for (Order order : orders) {
|
||||
criteria.addOrder(order);
|
||||
}
|
||||
}
|
||||
|
||||
// 查询总数
|
||||
criteria.setProjection(Projections.rowCount());
|
||||
Number result = (Number) criteria.uniqueResult();
|
||||
int count = result.intValue();
|
||||
pList.setCount(count);
|
||||
criteria.setProjection(null);
|
||||
// 查询集合
|
||||
if(start >= 0 && limit > 0) {
|
||||
criteria.setFirstResult(start);
|
||||
criteria.setMaxResults(limit);
|
||||
}
|
||||
List<T> list = criteria.list();
|
||||
pList.setList(list);
|
||||
return pList;
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Criteria查询
|
||||
* @param clazz
|
||||
* @param criterions
|
||||
* @param orders
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> findByCriteria(final Class<T> clazz, final List<Criterion> criterions, final List<Order> orders) {
|
||||
try {
|
||||
Criteria criteria = getCurrentSession().createCriteria(clazz);
|
||||
if (CollectionUtils.isNotEmpty(criterions)) {
|
||||
for (Criterion criterion : criterions) {
|
||||
criteria.add(criterion);
|
||||
}
|
||||
}
|
||||
if (CollectionUtils.isNotEmpty(orders)) {
|
||||
for (Order order : orders) {
|
||||
criteria.addOrder(order);
|
||||
}
|
||||
}
|
||||
return criteria.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Criteria查询
|
||||
* @param clazz
|
||||
* @param criterions
|
||||
* @param orders
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<T> findByCriteria(final Class<T> clazz, final List<Criterion> criterions, final List<Order> orders, final int start, final int limit) {
|
||||
try {
|
||||
Criteria criteria = getCurrentSession().createCriteria(clazz);
|
||||
for (Criterion criterion : criterions) {
|
||||
criteria.add(criterion);
|
||||
}
|
||||
for (Order order : orders) {
|
||||
criteria.addOrder(order);
|
||||
}
|
||||
if(start >= 0 && limit > 0) {
|
||||
criteria.setFirstResult(start);
|
||||
criteria.setMaxResults(limit);
|
||||
}
|
||||
return criteria.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Criteria查询
|
||||
* @param clazz
|
||||
* @param criterions
|
||||
* @param orders
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<?> findByCriteria(final Class<T> clazz, final List<Criterion> criterions, final List<Order> orders, final Projection projection) {
|
||||
try {
|
||||
Criteria criteria = getCurrentSession().createCriteria(clazz);
|
||||
for (Criterion criterion : criterions) {
|
||||
criteria.add(criterion);
|
||||
}
|
||||
for (Order order : orders) {
|
||||
criteria.addOrder(order);
|
||||
}
|
||||
criteria.setProjection(projection);
|
||||
return criteria.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Criteria查询
|
||||
* @param clazz
|
||||
* @param criterions
|
||||
* @param orders
|
||||
* @param projection
|
||||
* @param start
|
||||
* @param limit
|
||||
* @return
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public List<?> findByCriteria(final Class<T> clazz, final List<Criterion> criterions, final List<Order> orders, final Projection projection, final int start, final int limit) {
|
||||
try {
|
||||
Criteria criteria = getCurrentSession().createCriteria(clazz);
|
||||
for (Criterion criterion : criterions) {
|
||||
criteria.add(criterion);
|
||||
}
|
||||
for (Order order : orders) {
|
||||
criteria.addOrder(order);
|
||||
}
|
||||
criteria.setProjection(projection);
|
||||
if(start >= 0 && limit > 0) {
|
||||
criteria.setFirstResult(start);
|
||||
criteria.setMaxResults(limit);
|
||||
}
|
||||
return criteria.list();
|
||||
} catch (Exception e) {
|
||||
logger.error("查询出错", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public boolean doWork(final String sql, final List<Object[]> params) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
getCurrentSession().doWork(new Work() {
|
||||
@Override
|
||||
public void execute(Connection connection) throws SQLException {
|
||||
BatchSQLUtil sqlUtil = new BatchSQLUtil(connection, sql);
|
||||
for (Object[] param : params) {
|
||||
sqlUtil.addCount(param);
|
||||
}
|
||||
sqlUtil.commit();
|
||||
}
|
||||
});
|
||||
flag = true;
|
||||
} catch (Exception e) {
|
||||
logger.error("doWork出错", e);
|
||||
throw e;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package javautils.jdbc.util;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class BatchSQLUtil {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(BatchSQLUtil.class);
|
||||
|
||||
private Connection conn;
|
||||
private PreparedStatement ps;
|
||||
|
||||
public BatchSQLUtil(Connection conn, String sql) {
|
||||
try {
|
||||
this.conn = conn;
|
||||
this.conn.setAutoCommit(false);
|
||||
ps = this.conn.prepareStatement(sql);
|
||||
} catch (Exception e) {
|
||||
logger.error("BatchSQLUtil创建异常", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void addCount(Object[] param) {
|
||||
try {
|
||||
for (int i = 0; i < param.length; i++) {
|
||||
ps.setObject(i + 1, param[i]);
|
||||
}
|
||||
ps.addBatch();
|
||||
} catch (SQLException e) {
|
||||
logger.error("addCount异常", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void commit() {
|
||||
try {
|
||||
ps.executeBatch();
|
||||
conn.commit();
|
||||
ps.clearBatch();
|
||||
} catch (SQLException e) {
|
||||
logger.error("commit异常", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void close() {
|
||||
try {
|
||||
ps.close();
|
||||
conn.close();
|
||||
} catch (SQLException e) {
|
||||
logger.error("close异常", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package javautils.jdbc.util;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class SQLUtil {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SQLUtil.class);
|
||||
|
||||
// ------------------------------- 增删改通用 -------------------------------//
|
||||
public boolean aduSql(Connection conn, String sql) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
if (conn != null) {
|
||||
PreparedStatement ps = conn.prepareStatement(sql);
|
||||
ps.executeUpdate();
|
||||
ps.close();
|
||||
flag = true;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("aduSql异常", e);
|
||||
flag = false;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
public static boolean aduSql(Connection conn, String sql, Object[] params) {
|
||||
boolean flag = false;
|
||||
try {
|
||||
if (conn != null) {
|
||||
PreparedStatement ps = conn.prepareStatement(sql);
|
||||
if (params != null) {
|
||||
for (int i = 0; i < params.length; i++) {
|
||||
ps.setObject(i + 1, params[i]);
|
||||
}
|
||||
}
|
||||
ps.executeUpdate();
|
||||
flag = true;
|
||||
ps.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("aduSql异常", e);
|
||||
flag = false;
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
public static List<Object[]> exList(Connection conn, String sql, Object params[]) {
|
||||
ArrayList<Object[]> list = new ArrayList<Object[]>();
|
||||
try {
|
||||
if (conn != null) {
|
||||
PreparedStatement ps = conn.prepareStatement(sql);
|
||||
if (params != null) {
|
||||
for (int i = 0; i < params.length; i++) {
|
||||
ps.setObject(i + 1, params[i]);
|
||||
}
|
||||
}
|
||||
ResultSet rs = ps.executeQuery();
|
||||
while (rs.next()) {
|
||||
int columns = rs.getMetaData().getColumnCount();
|
||||
Object[] objArr = new Object[columns];
|
||||
for (int i = 0; i < columns; i++) {
|
||||
objArr[i] = rs.getObject(i + 1);
|
||||
}
|
||||
list.add(objArr);
|
||||
}
|
||||
rs.close();
|
||||
ps.close();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("exList异常", e);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package javautils.json;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
public class JacksonUtil {
|
||||
|
||||
public static String toJSON(Object o) {
|
||||
try {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
return objectMapper.writeValueAsString(o);
|
||||
} catch (JsonProcessingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static <T> T toObject(String json, Class<T> clazz) {
|
||||
try {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
return objectMapper.readValue(json, clazz);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package javautils.list;
|
||||
|
||||
import javautils.StringUtil;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class ListUtil {
|
||||
|
||||
/**
|
||||
* 高性能删除全部
|
||||
*/
|
||||
public static LinkedList removeAll(LinkedList src, LinkedList list){
|
||||
if (src == null || src.isEmpty() || list == null || list.isEmpty()) {
|
||||
return src;
|
||||
}
|
||||
|
||||
HashSet oth = new HashSet(list);
|
||||
return removeAll(src, oth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 高性能删除全部
|
||||
*/
|
||||
public static LinkedList removeAll(LinkedList src, HashSet oth){
|
||||
if (src == null || src.isEmpty() || oth == null || oth.isEmpty()) {
|
||||
return src;
|
||||
}
|
||||
|
||||
Iterator iter = src.iterator();//采用Iterator迭代器进行数据的操作
|
||||
while(iter.hasNext()){
|
||||
if(oth.contains(iter.next())){
|
||||
iter.remove();
|
||||
}
|
||||
}
|
||||
return src;
|
||||
}
|
||||
|
||||
/**
|
||||
* 高性能删除全部
|
||||
*/
|
||||
public static Set removeAll(Set src, Set oth){
|
||||
if (src == null || src.isEmpty() || oth == null || oth.isEmpty()) {
|
||||
return src;
|
||||
}
|
||||
|
||||
Iterator iter = src.iterator();//采用Iterator迭代器进行数据的操作
|
||||
while(iter.hasNext()){
|
||||
if(oth.contains(iter.next())){
|
||||
iter.remove();
|
||||
}
|
||||
}
|
||||
|
||||
return src;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Object数组转int数组
|
||||
* @param o
|
||||
* @return
|
||||
*/
|
||||
public static int[] transObjectToInt(Object[] o) {
|
||||
int[] t = new int[o.length];
|
||||
for (int i = 0; i < o.length; i++) {
|
||||
if(o[i] instanceof Integer) {
|
||||
t[i] = (Integer)o[i];
|
||||
}
|
||||
if(o[i] instanceof String) {
|
||||
String s = (String)o[i];
|
||||
if(StringUtil.isIntegerString(s)) {
|
||||
t[i] = Integer.parseInt(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/**
|
||||
* 集合转成String
|
||||
* @param list
|
||||
* @return
|
||||
*/
|
||||
public static String transListToString(List<?> list) {
|
||||
StringBuffer sb = new StringBuffer();
|
||||
for (Object obj : list) {
|
||||
sb.append(String.valueOf(obj) + ", ");
|
||||
}
|
||||
if(list.size() > 0) {
|
||||
return sb.substring(0, sb.length() - 2);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user