Commit d8b0b827 by yanlveming

同步

parent 54d8a02e
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd
">
<context:annotation-config />
<context:component-scan base-package="com.library" />
<!-- 支持上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
<!-- 开辟自启线程 -->
<bean id="springContextUtil" class="com.library.util.SpringContextUtil"></bean>
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis.xml"></property>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<mybatis:scan base-package="com.library.mapper" />
</beans>
\ No newline at end of file
package com.baidu.ueditor.um;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.util.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import Decoder.BASE64Decoder;
import javax.servlet.http.HttpServletRequest;
/**
* UEditor文件上传辅助类
*
*/
public class Uploader {
// 输出文件地址
private String url = "";
// 上传文件名
private String fileName = "";
// 状态
private String state = "";
// 文件类型
private String type = "";
// 原始文件名
private String originalName = "";
// 文件大小
private long size = 0;
private HttpServletRequest request = null;
private String title = "";
// 保存路径
private String savePath = "upload";
// 文件允许格式
private String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
// 文件大小限制,单位KB
private int maxSize = 10000;
private HashMap<String, String> errorInfo = new HashMap<String, String>();
public Uploader(HttpServletRequest request) {
this.request = request;
HashMap<String, String> tmp = this.errorInfo;
tmp.put("SUCCESS", "SUCCESS"); //默认成功
tmp.put("NOFILE", "未包含文件上传域");
tmp.put("TYPE", "不允许的文件格式");
tmp.put("SIZE", "文件大小超出限制");
tmp.put("ENTYPE", "请求类型ENTYPE错误");
tmp.put("REQUEST", "上传请求异常");
tmp.put("IO", "IO异常");
tmp.put("DIR", "目录创建失败");
tmp.put("UNKNOWN", "未知错误");
}
public void upload() throws Exception {
boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
if (!isMultipart) {
this.state = this.errorInfo.get("NOFILE");
return;
}
DiskFileItemFactory dff = new DiskFileItemFactory();
String savePath = this.getFolder(this.savePath);
dff.setRepository(new File(savePath));
try {
ServletFileUpload sfu = new ServletFileUpload(dff);
sfu.setSizeMax(this.maxSize * 1024);
sfu.setHeaderEncoding("utf-8");
FileItemIterator fii = sfu.getItemIterator(this.request);
while (fii.hasNext()) {
FileItemStream fis = fii.next();
if (!fis.isFormField()) {
this.originalName = fis.getName().substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1);
if (!this.checkFileType(this.originalName)) {
this.state = this.errorInfo.get("TYPE");
continue;
}
this.fileName = this.getName(this.originalName);
this.type = this.getFileExt(this.fileName);
this.url = savePath + "/" + this.fileName;
BufferedInputStream in = new BufferedInputStream(fis.openStream());
File file = new File(this.getPhysicalPath(this.url));
FileOutputStream out = new FileOutputStream( file );
BufferedOutputStream output = new BufferedOutputStream(out);
Streams.copy(in, output, true);
this.state=this.errorInfo.get("SUCCESS");
this.size = file.length();
//UE中只会处理单张上传,完成后即退出
break;
} else {
String fname = fis.getFieldName();
//只处理title,其余表单请自行处理
if(!fname.equals("pictitle")){
continue;
}
BufferedInputStream in = new BufferedInputStream(fis.openStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer result = new StringBuffer();
while (reader.ready()) {
result.append((char)reader.read());
}
this.title = new String(result.toString().getBytes(),"utf-8");
reader.close();
}
}
} catch (SizeLimitExceededException e) {
this.state = this.errorInfo.get("SIZE");
} catch (InvalidContentTypeException e) {
this.state = this.errorInfo.get("ENTYPE");
} catch (FileUploadException e) {
this.state = this.errorInfo.get("REQUEST");
} catch (Exception e) {
this.state = this.errorInfo.get("UNKNOWN");
}
}
/**
* 接受并保存以base64格式上传的文件
* @param fieldName
*/
public void uploadBase64(String fieldName){
String savePath = this.getFolder(this.savePath);
String base64Data = this.request.getParameter(fieldName);
this.fileName = this.getName("test.png");
this.url = savePath + "/" + this.fileName;
BASE64Decoder decoder = new BASE64Decoder();
try {
File outFile = new File(this.getPhysicalPath(this.url));
OutputStream ro = new FileOutputStream(outFile);
byte[] b = decoder.decodeBuffer(base64Data);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
ro.write(b);
ro.flush();
ro.close();
this.state=this.errorInfo.get("SUCCESS");
} catch (Exception e) {
this.state = this.errorInfo.get("IO");
}
}
/**
* 文件类型判断
*
* @param fileName
* @return
*/
private boolean checkFileType(String fileName) {
Iterator<String> type = Arrays.asList(this.allowFiles).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileName.toLowerCase().endsWith(ext)) {
return true;
}
}
return false;
}
/**
* 获取文件扩展名
*
* @return string
*/
private String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf("."));
}
/**
* 依据原始文件名生成新文件名
* @return
*/
private String getName(String fileName) {
Random random = new Random();
return this.fileName = "" + random.nextInt(10000)
+ System.currentTimeMillis() + this.getFileExt(fileName);
}
/**
* 根据字符串创建本地目录 并按照日期建立子目录返回
* @param path
* @return
*/
private String getFolder(String path) {
SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
path += "/" + formater.format(new Date());
File dir = new File(this.getPhysicalPath(path));
if (!dir.exists()) {
try {
dir.mkdirs();
} catch (Exception e) {
this.state = this.errorInfo.get("DIR");
return "";
}
}
return path;
}
/**
* 根据传入的虚拟路径获取物理路径
*
* @param path
* @return
*/
private String getPhysicalPath(String path) {
String servletPath = this.request.getServletPath();
String realPath = this.request.getSession().getServletContext()
.getRealPath(servletPath);
return new File(realPath).getParent() +"/" +path;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public void setAllowFiles(String[] allowFiles) {
this.allowFiles = allowFiles;
}
public void setMaxSize(int size) {
this.maxSize = size;
}
public long getSize() {
return this.size;
}
public String getUrl() {
return this.url;
}
public String getFileName() {
return this.fileName;
}
public String getState() {
return this.state;
}
public String getTitle() {
return this.title;
}
public String getType() {
return this.type;
}
public String getOriginalName() {
return this.originalName;
}
}
package com.library.bean;
/**
* 权限bean
* @author Administrator
*
*/
public class PowerBean {
public String name;
public Integer code;
public PowerBean(String name,Integer code){
this.name=name;
this.code=code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
package com.library.bean;
import java.sql.Timestamp;
/**
* 用户信息
* @author Administrator
*
*/
public class User {
private int id;
private String phone_num;//普通用户注册号码
private String password;//密码(MD5加密)
private String nick_name;//用户昵称
private Timestamp time;//注册时间
private int role_root;//权限角色
private int user_not;//用户删除(删除:-1,否:1)
private int manager_not;//是否管理员(否:-1,是:1)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPhone_num() {
return phone_num;
}
public void setPhone_num(String phone_num) {
this.phone_num = phone_num;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nick_name) {
this.nick_name = nick_name;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public int getRole_root() {
return role_root;
}
public void setRole_root(int role_root) {
this.role_root = role_root;
}
public int getUser_not() {
return user_not;
}
public void setUser_not(int user_not) {
this.user_not = user_not;
}
public int getManager_not() {
return manager_not;
}
public void setManager_not(int manager_not) {
this.manager_not = manager_not;
}
}
package com.library.config;
/**
* 配置内容
* @author Administrator
*
*/
public class ConfigCon {
// public static String BaseAddress="http://192.168.1.105:8080/LuckFix";//最根本的地址
public static String BaseAddress="http://xm-fzw.com";//最根本的地址
/**微信公众号支付配置**/
public static String WeChat_Appid="";//微信开放平台审核通过的应用APPID
public static String WeChat_Mch_id="";//微信支付分配的商户号
public static String WeChat_AppSecret="";
public static String AddressCreateOrder="https://api.mch.weixin.qq.com/pay/unifiedorder";//统一下单接口
/**API安全密钥*/
public static String WeChat_APIKey="";
/**微信App支付配置**/
public static String WeChatAPP_Appid="";//微信开放平台审核通过的应用APPID
public static String WeChatAPP_Mch_id="";//微信支付分配的商户号
public static String WeChatAPP_AppSecret="";
/**API安全密钥*/
public static String WeChatAPP_APIKey="";
public static String WeChat_Notify_urlMyOrder=BaseAddress+"/Interface/wechatPay_myOrder.do";//接收--商城订单支付通知
public static String WeChat_Notify_urlshopBond=BaseAddress+"/Interface/wechatPay_shopBond.do";//接收--商家保证金支付回调通知
public static String WeChat_Notify_urlOrderDelivery=BaseAddress+"/Interface/wechatPay_OrderDelivery.do";//接收--用户接单配送支付保证金
public static String WeChat_Notify_urlShopPublicOrderDelivery=BaseAddress+"/Interface/wechatPay_ShopPublicOrderDelivery.do";//接收--商家发布接单配送订单支付配送费用
public static String WeChat_Notify_urlOneKeyFoot=BaseAddress+"/Interface/wechatPay_OneKeyFoot.do";//接收--一键脚步费用预支付
public static String WeChat_Notify_urlOneKeyTimePay=BaseAddress+"/Interface/wechatPay_OneKeyTimePay.do";//接收--一键模块按时费用支付
public static String WeChat_Notify_urlTransferRecordPay=BaseAddress+"/Interface/WeChat_Notify_urlTransferRecordPay.do";//接收--转账给商家支付
public static String WeChat_Notify_Reward=BaseAddress+"/Interface/WeChat_Notify_Reward.do";//接收--转账给用户支付(赏金)
/**
* 小程序相关配置信息
*/
public static String SmallAppid = ""; //小程序唯一标识
public static String SmallSecret = ""; //小程序的 app secret
public static String Small_Mch_id = "";//微信支付分配的商户号
/**API安全密钥*/
public static String Small_APIKey = "";
}
package com.library.config;
/**
* 共有名称
*
* @author Administrator
*/
public class NameValue {
public static String User_Session = "User_Session";//保存在session的用户昵称
public static String Admin_Session = "Admin_Session";//保存在session的管理员
public static String User_Code_Session = "User_Code_Session";//保存在session的管理员
public static String User_Phone_Session = "User_Phone_Session";//保存在session的管理员
public static String goToPage = "goToPage";//微信公众号免登陆后跳转到页面名称保存在session的名称
public static String goToPageTip = "goToPageTip";//微信公众号免登陆后跳转到页面名称保存在session的名称
public static String Table_admin = "pre_dz_pay_admin";//对应数据库表的名称
public static String Table_user = "pre_dz_pay_user";//会员表
public static String Table_automatic_queue = "pre_dz_pay_automatic_queue";//充值队列表
public static String Table_order_log = "pre_dz_pay_order_log";//订单日志表
public static String Table_order = "pre_dz_pay_order";//订单表
}
package com.library.config;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.library.bean.PowerBean;
import com.library.model.AdminModel;
import com.library.util.Tools;
/*
* 权限配置
*/
public class PowerConfig {
public static Integer ProductManage=1001;//产品管理
public static Integer ProjectManage=1002;//项目管理
public static Integer MemberManager=1003;//会员管理
public static Integer OrderManager=1004;//订单管理
public static Integer SystemSetting=1005;//系统设置
public static List<PowerBean> powerBeans;//权限集合
/**
* 获取权限集合
*/
public static List<PowerBean> getPowerList(){
if(powerBeans==null){
powerBeans = new ArrayList<PowerBean>();
powerBeans.add(new PowerBean("产品管理", ProductManage));
powerBeans.add(new PowerBean("项目管理", ProjectManage));
powerBeans.add(new PowerBean("会员管理", MemberManager));
powerBeans.add(new PowerBean("订单管理", OrderManager));
powerBeans.add(new PowerBean("系统设置", SystemSetting));
}
return powerBeans;
}
/**
* 判断是否拥有该权限
* 参数:请求头对象,权限代号
* ture 有,false没有
*/
public static boolean isHasPower(HttpServletRequest request, Integer Code){
AdminModel adminModel =(AdminModel) request.getSession().getAttribute(NameValue.Admin_Session);
if(Code==-1){
return false;
}
if(adminModel==null){
return false;
}
if(adminModel.getAdmin_type()==1){//超级管理员,直接过
return true;
}
List<Integer> list = Tools.gson.fromJson(adminModel.getJurisdiction(), Tools.IntegerListType);
if(list==null){
return false;
}
for(Integer value :list){
if(value.equals(Code)){//有该权限
return true;
}
}
return false;
}
/**
* 判断是否超级管理员
*/
public static boolean isSuperAdmin(HttpServletRequest request){
AdminModel adminModel =(AdminModel) request.getSession().getAttribute(NameValue.Admin_Session);
if(adminModel!=null && adminModel.getAdmin_type()==1){
return true;
}
return false;
}
}
package com.library.controller;
import com.library.respcode.ServerResponse;
import com.library.service.AdminService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
/**
* 管理员操作
* @author Administrator
*
*/
@Controller
@RequestMapping("AdminManage")
public class AdminController {
@Resource
private AdminService adminService;
//管理员登陆
@ResponseBody
@RequestMapping("adminOpear")
private ServerResponse adminOpear() {
return adminService.adminOpear();
}
}
package com.library.controller;
import com.library.respcode.ServerResponse;
import com.library.service.AdminService;
import com.library.service.CommService;
import com.library.util.QiniuUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
/*
* @项目名: yunVpay
* @包名: com.library.controller
* @文件名: CommonController
* @创建者: zhouzhuo
* @创建时间: 2018/11/1 14:50
* @描述: TODO
*/
@Controller
@RequestMapping("/Common")
public class CommonController{
@Resource
private CommService commService;
//获取七牛云的token
@ResponseBody
@RequestMapping("/FindQNYToken")
private ServerResponse FindQNYToken(){
String token = QiniuUtils.getUpToken();
return ServerResponse.createBySuccess(token);
}
//Recharge
@ResponseBody
@RequestMapping("recharge")
private ServerResponse recharge() {
return commService.Recharge();
}
//登录
@ResponseBody
@RequestMapping("adminLogin")
private ServerResponse adminLogin() {
return commService.adminLogin();
}
}
package com.library.mapper;
import org.apache.ibatis.annotations.Param;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
/**
* 后台Mapper
* @author Administrator
*
*/
public interface AdminMapper {
/**
* 分页查找会员
*/
public List<Map<String,Object>> FindAllUser(@Param("page") int page, @Param("number") int number);
/**
* 查找产品
*/
public List<Map<String ,Object >> FindAllProductByAdmin(@Param("page") Integer page,
@Param("number") Integer number,
@Param("by_type_id")Integer by_type_id,
@Param("startTime")Timestamp startTime,
@Param("endTime")Timestamp endTime);
/**
* 查找参与夺宝人员
* @param page
* @param number
* @param state
* @param startTime
* @param endTime
* @return
*/
public List<Map<String , Object>> FindParticipant(@Param("page") Integer page,
@Param("number") Integer number,
@Param("id")Integer id,
@Param("state")Integer state,
@Param("startTime")Timestamp startTime,
@Param("endTime")Timestamp endTime);
/**
* 按状态获取审核充值记录
*/
public List<Map<String,Object>> FinfAuditRechargeByStatus(@Param("status")int status,@Param("start")Integer start,@Param("number")Integer number
,@Param("key_word")String key_word);
/**
* 查找轮播图通过id
*/
public Map<String,Object> findACarousel(@Param("id")int id);
/**
* 获取轮播图
*/
public List<Map<String,Object>> FindHomeImage(@Param("start")Integer start,@Param("number")Integer number);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.library.mapper.AdminMapper">
<!-- 分页查询会员数据 -->
<select id="FindAllUser" resultType="map" parameterType="map">
SELECT
*
FROM
user
limit #{page},#{number}
</select>
<!-- 查询产品数据 -->
<select id="FindAllProductByAdmin" resultType="map" parameterType="map">
SELECT
p.*,
pt.product_type_name,
ad.admin_name
FROM
product AS p
INNER JOIN product_type AS pt ON p.by_type_id = pt.id
INNER JOIN admin AS ad ON p.by_adminid = ad.id
<where>
<if test="by_type_id != null">
pt.id = #{by_type_id}
</if>
<if test="startTime != null and endTime != null">
and p.time <![CDATA[ >= ]]> #{startTime}
and p.time <![CDATA[ <= ]]> #{endTime}
</if>
</where>
order by p.time desc
<if test="page != null and number != null">
limit #{page},#{number}
</if>
</select>
<!-- 查询参与夺宝的人员 -->
<select id="FindParticipant" resultType="map" parameterType="map">
select pp.* , p.product_name , u.vpay_name
from participant as pp left join product as p on pp.by_product_id=p.id left join user as u on pp.by_user_id=u.id
<where>
pp.by_product_id = p.id
<if test="id != null">
and pp.by_product_id = #{id}
</if>
<if test="state != null">
and pp.state = #{state}
</if>
</where>
group by pp.id order by pp.time DESC
<if test="page != null and number != null">
limit #{page} , #{number}
</if>
</select>
<select id="FinfAuditRechargeByStatus" resultType="map" parameterType="map">
select bl.*,u.nickname,u.vpay_name,u.phone,u.balance
from balance_log as bl left join user as u on u.id=bl.user_id
where bl.state=#{status}
<if test="key_word!=null">
and (u.vpay_name like #{key_word} or u.nickname like #{key_word} or u.phone like #{key_word})
</if>
<if test="start!=null">
limit #{start} , #{number}
</if>
</select>
<select id="findACarousel" resultType="map" parameterType="map">
SELECT
hi.id,
hi.image,
hi.order_by,
hi.state,
hi.product_id,
hi.time,
p.product_name
FROM
home_image AS hi
LEFT JOIN product AS p ON hi.product_id = p.id
WHERE hi.id=#{id}
</select>
<!-- 分页查找轮播图 -->
<select id="FindHomeImage" resultType="map" parameterType="map">
select p.product_name,hm.* from home_image as hm left join product as p on p.id=hm.product_id
<if test="start!=null">
limit #{start},#{number}
</if>
</select>
</mapper>
package com.library.mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Map;
/**
* Created by Administrator on 2018\11\22 0022.
*/
public interface AutomaticQueueMapper {
/**
* 得到最早的一条数据
*
* @return
*/
public Map<String, Object> selectEarlyOne();
/**
* 根据订单编号获取到订单信息
* @param order_number
* @return
*/
public Map<String, Object> selectOrderByNumber(@Param("order_number") String order_number);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.library.mapper.AutomaticQueueMapper">
<!-- 查找最早的一条数据 -->
<select id="selectEarlyOne" resultType="map" parameterType="map">
select * from pre_dz_pay_automatic_queue where status = 0 order by id asc limit 0,1
</select>
<select id="selectOrderByNumber" resultType="map" parameterType="map">
select * from pre_dz_pay_order where order_number = #{order_number};
</select>
</mapper>
package com.library.mapper;
import com.library.model.UserModel;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* 用户的Dao
*
* @author Administrator
*/
public interface CommMapper {
/**
* 通过opneid查询会员信息
*/
public UserModel selectForOpenid(@Param("openid") String openid);
/**
* 查找最新的商品
*
* @param page
* @param number
* @return
*/
public List<Map<String, Object>> findTheLatestProducts(@Param("page") int page, @Param("number") int number);
/**
* 查找热门商品
*
* @param page
* @param number
* @return
*/
public List<Map<String, Object>> findPopularProducts(@Param("page") int page, @Param("number") int number);
/**
* 查找即将开奖商品
*
* @param page
* @param number
* @return
*/
public List<Map<String, Object>> findUpcomingItems(@Param("page") int page, @Param("number") int number);
/**
* 查找已开奖的信息
*
* @param page
* @param number
* @return
*/
public List<Map<String, Object>> findTheWinningInformation(@Param("page") int page, @Param("number") int number);
/**
* 中奖纪录
*
* @param page
* @param number
* @return
*/
public List<Map<String, Object>> winningAllRecord(@Param("page") int page, @Param("number") int number);
/**
* 最新开奖
*
* @return
*/
public List<Map<String, Object>> latestDraw();
/**
* 查找全部商品
*
* @param page
* @param number
* @return
*/
public List<Map<String, Object>> findAllProducts(@Param("page") int page, @Param("number") int number);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.library.mapper.CommMapper">
<!-- 查询用户 -->
<select id="selectForOpenid" resultType="com.library.model.UserModel" parameterType="map">
select * from user where openid_wx = #{openid}
</select>
<!--查找最新商品-->
<select id="findTheLatestProducts" parameterType="map" resultType="map">
SELECT
p.*,
(SELECT py.product_type_name FROM product_type AS py where py.id=p.by_type_id) AS type_name,
IFNULL((
SELECT
SUM(number)
FROM
participant AS pp
WHERE
pp.by_product_id = p.id
AND state = 2
),0) AS participate_number
FROM
product AS p
WHERE
p.state = 1
AND p.start_time <![CDATA[ < ]]> now()
ORDER BY
p.time DESC
LIMIT #{page},#{number}
</select>
<!--查找热门商品-->
<select id="findPopularProducts" parameterType="map" resultType="map">
SELECT
p.*,
(
SELECT
py.product_type_name
FROM
product_type AS py
WHERE
py.id = p.by_type_id
) AS type_name,
IFNULL((
SELECT
SUM(number)
FROM
participant AS pp
WHERE
pp.by_product_id = p.id
AND state = 2
),0) AS participate_number
FROM
product AS p
WHERE
p.state = 1
AND p.start_time <![CDATA[ < ]]> now()
ORDER BY
participate_number DESC
LIMIT #{page},#{number}
</select>
<!--查找即将开奖商品-->
<select id="findUpcomingItems" parameterType="map" resultType="map">
SELECT
p.*,
(
SELECT
py.product_type_name
FROM
product_type AS py
WHERE
py.id = p.by_type_id
) AS type_name,
IFNULL((
SELECT
SUM(number)
FROM
participant AS pp
WHERE
pp.by_product_id = p.id
AND state = 2
),0) AS participate_number
FROM
product AS p
WHERE
p.state = 1
AND p.start_time <![CDATA[ < ]]> now()
ORDER BY
p.need_number-participate_number ASC
LIMIT #{page},#{number}
</select>
<!--查找已开奖的信息-->
<select id="findTheWinningInformation" parameterType="map" resultType="map">
SELECT
pp.prevail_price,
pp.lucky_number,
pp.state,
p.product_name,
u.nickname,
u.vpay_name,
u.user_image,
p.issue,
pp.id,
p.finish_time
FROM
participant AS pp
INNER JOIN product AS p ON pp.by_product_id = p.id AND pp.lucky_number = p.winning_number
INNER JOIN `user` AS u ON pp.by_user_id = u.id
WHERE
p.state = 2
ORDER BY
p.finish_time DESC
LIMIT #{page},#{number}
</select>
<!--中奖纪录-->
<select id="winningAllRecord" resultType="map" parameterType="map">
SELECT
p.*,
pp.by_user_id,
pp.lucky_number,
u.nickname,
u.vpay_name,
IFNULL((
SELECT
SUM(number)
FROM
participant AS pp
WHERE
pp.by_product_id = p.id
AND state = 2
),0) AS participate_number
FROM
product AS p
INNER JOIN participant AS pp ON p.winning_number = pp.lucky_number AND p.id = pp.by_product_id AND pp.state = 2
INNER JOIN `user` AS u ON pp.by_user_id = u.id
WHERE p.finish_time <![CDATA[ <= ]]> now()
ORDER BY
p.issue DESC
LIMIT #{page},#{number}
</select>
<!--正在开奖-->
<select id="latestDraw" resultType="map" parameterType="map">
SELECT
p.id,
p.product_name,
p.price,
p.product_desc,
p.product_subheading,
p.product_image,
p.issue,
p.need_number,
p.state,
p.time,
p.finish_time,
(
SELECT
py.product_type_name
FROM
product_type AS py
WHERE
py.id = p.by_type_id
) AS type_name,
IFNULL((
SELECT
SUM(number)
FROM
participant AS pp
WHERE
pp.by_product_id = p.id
AND state = 2
),0) AS participate_number
FROM
product AS p
WHERE
p.start_time <![CDATA[ < ]]> now()
AND
p.finish_time <![CDATA[ > ]]> now()
AND p.state=2
ORDER BY
p.finish_time ASC
</select>
<!--查找全部商品-->
<select id="findAllProducts" resultType="map" parameterType="map">
SELECT
p.*,
(
SELECT
py.product_type_name
FROM
product_type AS py
WHERE
py.id = p.by_type_id
) AS type_name,
IFNULL((
SELECT
SUM(number)
FROM
participant AS pp
WHERE
pp.by_product_id = p.id
AND state = 2
),0) AS participate_number
FROM
product AS p
WHERE
p.state = 1 AND
p.start_time <![CDATA[ < ]]> now()
LIMIT #{page},#{number}
</select>
</mapper>
package com.library.mapper;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
public interface CurrencyMapper {
public void DeleteDataById(@Param("tableName")String tableName,@Param("id")int id);
public Map<String, Object> FindDataById(@Param("tableName")String tableName,@Param("id")int id);
public List<Map<String, Object>> FindDataListById(@Param("tableName")String tableName,@Param("id_all")List<Integer> id_all);
public List<Map<String, Object>> FindDataListByPaging(@Param("tableName")String tableName,@Param("start")int start,@Param("number")int number);
/**
* 统计表的数据
*/
public Map<String, Object> CountTableNumber(@Param("tableName")String tableName);
/**
* 条件集合查询,“where id=id”
*/
public List<Map<String, Object>> FindDataListWhere(@Param("tableName")String tableName,@Param("start")int start,
@Param("number")int number,@Param("where")String where);
/**
* 查询某个表格的所有数据
*/
public List<Map<String, Object>> findTable(@Param("tableName")String tableName);
/**
* 通用接口--修改数据
*/
public void updateTableForMysql(@Param("mysql")String mysql);
/**
* 通用接口--增加新的数据
*/
public void AddTableForMysql(@Param("mysql")String mysql);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.library.mapper.CurrencyMapper">
<delete id="DeleteDataById" parameterType="map" statementType="STATEMENT">
delete from ${tableName} where id=${id}
</delete>
<select id="FindDataById" resultType="map">
select * from ${tableName}
where id=${id}
</select>
<!-- 获得指定id集合的需要资料 -->
<select id="FindDataListById" parameterType="map" resultType="map">
select * from ${tableName} where id in
<foreach item="item" index="index" collection="id_all" open="("
separator="," close=")">
#{item}
</foreach>
</select>
<!-- 分页查询数据表 -->
<select id="FindDataListByPaging" parameterType="map" resultType="map">
select * from ${tableName} limit #{start},#{number}
</select>
<!-- 统计表的数据 -->
<select id="CountTableNumber" resultType="map">
select count(*) from ${tableName}
</select>
<!-- 条件集合查询,“where id=id” -->
<select id="FindDataListWhere" parameterType="map" resultType="map">
select * from ${tableName} ${where} limit #{start},#{number}
</select>
<!-- 查询某个表格的所有数据 -->
<select id="findTable" parameterType="map" resultType="map">
select * from ${tableName}
</select>
<!-- 通用接口-修改数据 -->
<update id="updateTableForMysql" parameterType="map" >
${mysql}
</update>
<!-- 通用接口-增加新的数据 -->
<insert id="AddTableForMysql" parameterType="map">
${mysql}
</insert>
</mapper>
package com.library.model;
import java.sql.Timestamp;
/**
* Created by q9210 on 2018/8/9.
*/
public class AddressModel {
private Integer id;
private Integer user_id;//用户id
private String address;//详细位置
private String user_name;//收件人名称
private String phone;//联系电话
private Integer state;// 1:默认地址 0:非默认地址
private Timestamp time;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
}
package com.library.model;
import java.sql.Timestamp;
/**
* 管理员
* @author Administrator
*
*/
public class AdminModel {
private int id;
private String admin_name;//管理员名称
private String account;//手机号码
private String password;//登陆密码
private Timestamp time;//时间
private int admin_type;//账户类型:1、超级管理员,2普通管理员
private String jurisdiction;//储存权限代码号,json数据格式:{1,2}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAdmin_name() {
return admin_name;
}
public void setAdmin_name(String admin_name) {
this.admin_name = admin_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public int getAdmin_type() {
return admin_type;
}
public void setAdmin_type(int admin_type) {
this.admin_type = admin_type;
}
public String getJurisdiction() {
return jurisdiction;
}
public void setJurisdiction(String jurisdiction) {
this.jurisdiction = jurisdiction;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
}
package com.library.model;
import java.math.BigDecimal;
public class AutomaticQueueModel {
/**
* order_phone : 066301180
* order_money : 1.0
* id : 1
* order_num : 456b5f7e-916e-b222-8604-0dbcc41dbf72
* order_code_id : 121
* segment_id : 3
* status : 0
*/
private String order_phone; //充值手机号
private BigDecimal order_money; //充值金额(美元)
private int id;
private String order_num; //订单编号
private int order_code_id; //订单表id
private int segment_id; //对应手机服务商表的paygo_id
private int status; //0.等待充值,1充值处理中
public String getOrder_phone() {
return order_phone;
}
public void setOrder_phone(String order_phone) {
this.order_phone = order_phone;
}
public BigDecimal getOrder_money() {
return order_money;
}
public void setOrder_money(BigDecimal order_money) {
this.order_money = order_money;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOrder_num() {
return order_num;
}
public void setOrder_num(String order_num) {
this.order_num = order_num;
}
public int getOrder_code_id() {
return order_code_id;
}
public void setOrder_code_id(int order_code_id) {
this.order_code_id = order_code_id;
}
public int getSegment_id() {
return segment_id;
}
public void setSegment_id(int segment_id) {
this.segment_id = segment_id;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
\ No newline at end of file
package com.library.model;
import java.sql.Timestamp;
/*
* @项目名: yunVpay
* @包名: com.library.model
* @文件名: BalanceLogModel
* @创建者: zhouzhuo
* @创建时间: 2018/11/2 17:50
* @描述: TODO
*/
public class BalanceLogModel {
private int id;
private int user_id;
private int state;
private double operation_price;
private double after_price;
private Timestamp time;
private String remark;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public double getOperation_price() {
return operation_price;
}
public void setOperation_price(double operation_price) {
this.operation_price = operation_price;
}
public double getAfter_price() {
return after_price;
}
public void setAfter_price(double after_price) {
this.after_price = after_price;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
package com.library.model;
import java.sql.Timestamp;
/**
* Created by Administrator on 2018\11\2 0002.
*/
public class HomeImage {
public Integer id;
public String image;
public Integer order_by;//排序,越小越靠前
public Integer state;//1、不做跳转,2跳转到商品详情
public Integer product_id;// 当state=2时候有值,跳转的商品id
public Timestamp time;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getOrder_by() {
return order_by;
}
public void setOrder_by(Integer order_by) {
this.order_by = order_by;
}
public Integer getState() {
return state;
}
public void setState(Integer state) {
this.state = state;
}
public Integer getProduct_id() {
return product_id;
}
public void setProduct_id(Integer product_id) {
this.product_id = product_id;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
}
package com.library.model;
import java.sql.Timestamp;
/**
* Created by Administrator on 2018\11\23 0023.
*/
public class OrderLogModel {
private int id;
private String log_content; //内容描述
private int log_type; //1生成订单 ,2支付成功(系统处理中) 3.充值成功 4充值失败(人工处理)
private String log_order_number; //订单编号
private Timestamp time;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLog_content() {
return log_content;
}
public void setLog_content(String log_content) {
this.log_content = log_content;
}
public int getLog_type() {
return log_type;
}
public void setLog_type(int log_type) {
this.log_type = log_type;
}
public String getLog_order_number() {
return log_order_number;
}
public void setLog_order_number(String log_order_number) {
this.log_order_number = log_order_number;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
}
package com.library.model;
import java.math.BigDecimal;
import java.sql.Timestamp;
/**
* Created by Administrator on 2018\11\23 0023.
*/
public class OrderModel {
/**
* gid : 1
* create_time : Nov 16, 2018 5:31:06 PM
* user_name : 赶紧改名字
* paygo_time : Nov 23, 2018 10:12:05 AM
* order_number : 456b5f7e-916e-b222-8604-0dbcc41dbf72
* del_status : false
* pay_money : 1.0
* spid : 35
* pay_way : 微信支付
* pay_time : Nov 20, 2018 4:15:07 PM
* paygo_remark : 阿萨德
* money : 1.0
* user_id : 39
* phone : 066301180
* id : 121
* state : true
*/
private int gid;
private Timestamp create_time;
private String user_name;
private Timestamp paygo_time;
private String order_number; //订单编号
private int del_status; //删除状态 0未删除 1删除
private int spid;
private String pay_way;
private Timestamp pay_time;
private String paygo_remark;
private BigDecimal money; // 订单充值的金额价格 (美元)
private BigDecimal pay_money; // 支付金额(人民币)
private int user_id;
private String phone;
private int id;
private int state; //支付结果1.待支付,2支付成功(系统处理中) 3.充值成功 4充值失败(人工处理)
public int getGid() {
return gid;
}
public void setGid(int gid) {
this.gid = gid;
}
public Timestamp getCreate_time() {
return create_time;
}
public void setCreate_time(Timestamp create_time) {
this.create_time = create_time;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public Timestamp getPaygo_time() {
return paygo_time;
}
public void setPaygo_time(Timestamp paygo_time) {
this.paygo_time = paygo_time;
}
public String getOrder_number() {
return order_number;
}
public void setOrder_number(String order_number) {
this.order_number = order_number;
}
public int getDel_status() {
return del_status;
}
public void setDel_status(int del_status) {
this.del_status = del_status;
}
public BigDecimal getPay_money() {
return pay_money;
}
public void setPay_money(BigDecimal pay_money) {
this.pay_money = pay_money;
}
public int getSpid() {
return spid;
}
public void setSpid(int spid) {
this.spid = spid;
}
public String getPay_way() {
return pay_way;
}
public void setPay_way(String pay_way) {
this.pay_way = pay_way;
}
public Timestamp getPay_time() {
return pay_time;
}
public void setPay_time(Timestamp pay_time) {
this.pay_time = pay_time;
}
public String getPaygo_remark() {
return paygo_remark;
}
public void setPaygo_remark(String paygo_remark) {
this.paygo_remark = paygo_remark;
}
public BigDecimal getMoney() {
return money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
}
package com.library.model;
import java.sql.Timestamp;
/**
* Created by Administrator on 2018\10\31 0031.
*/
public class ParticipantModel {
/**
* prevail_price : 12.0
* update_time : Oct 31, 2018 6:19:29 PM
* by_user_id : 1
* by_product_id : 1
* id : 1
* state : 1
* time : Oct 31, 2018 6:20:09 PM
* lucky_number : 123231312
*/
private double prevail_price;
private Timestamp update_time;
private int by_user_id;
private int by_product_id;
private int id;
private int state;
private Timestamp time;
private String lucky_number;
private int by_address_id;
private int number;
public double getPrevail_price() {
return prevail_price;
}
public void setPrevail_price(double prevail_price) {
this.prevail_price = prevail_price;
}
public Timestamp getUpdate_time() {
return update_time;
}
public void setUpdate_time(Timestamp update_time) {
this.update_time = update_time;
}
public int getBy_user_id() {
return by_user_id;
}
public void setBy_user_id(int by_user_id) {
this.by_user_id = by_user_id;
}
public int getBy_product_id() {
return by_product_id;
}
public void setBy_product_id(int by_product_id) {
this.by_product_id = by_product_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public String getLucky_number() {
return lucky_number;
}
public void setLucky_number(String lucky_number) {
this.lucky_number = lucky_number;
}
public int getBy_address_id() {
return by_address_id;
}
public void setBy_address_id(int by_address_id) {
this.by_address_id = by_address_id;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
package com.library.model;
import java.sql.Timestamp;
/**
* 产品
*
* @author Administrator
*/
public class ProductModel {
/**
* winning_number : 23434
* product_subheading : sdfSds
* issue : 12312
* product_image : http://qiniu.xnsystem.com/imga15381478326221538147832622
* product_name : 老鼠沐浴露
* need_number : 84
* finish_time : Nov 9, 2018 6:19:34 PM
* product_desc : 这里有包很好的猫粮
* start_time : Oct 31, 2018 6:19:29 PM
* by_type_id : 42
* by_adminid : 3
* price : 0.01
* updata_time : Oct 31, 2018 6:19:04 PM
* id : 1
* state : 1
* time : Sep 27, 2018 1:32:27 PM
*/
private String product_image;// 产品图片
private String product_name;// 产品名称
private String product_desc;// 字段描述
private int by_type_id;// 对应的分类id
private int by_adminid;
private int id;
private int state;// 项目状态:1正在销售,2结束销售
private String winning_number;//幸运号码
private String product_subheading;//副标题
private int issue;//期号
private int need_number;//需要的人数
private Timestamp finish_time;//结束时间
private Timestamp start_time;//开始时间
private Timestamp updata_time;//更新时间
private double price;//价格
private Timestamp time;//添加时间
public String getProduct_image() {
return product_image;
}
public void setProduct_image(String product_image) {
this.product_image = product_image;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_desc() {
return product_desc;
}
public void setProduct_desc(String product_desc) {
this.product_desc = product_desc;
}
public int getBy_type_id() {
return by_type_id;
}
public void setBy_type_id(int by_type_id) {
this.by_type_id = by_type_id;
}
public int getBy_adminid() {
return by_adminid;
}
public void setBy_adminid(int by_adminid) {
this.by_adminid = by_adminid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getWinning_number() {
return winning_number;
}
public void setWinning_number(String winning_number) {
this.winning_number = winning_number;
}
public String getProduct_subheading() {
return product_subheading;
}
public void setProduct_subheading(String product_subheading) {
this.product_subheading = product_subheading;
}
public int getIssue() {
return issue;
}
public void setIssue(int issue) {
this.issue = issue;
}
public int getNeed_number() {
return need_number;
}
public void setNeed_number(int need_number) {
this.need_number = need_number;
}
public Timestamp getFinish_time() {
return finish_time;
}
public void setFinish_time(Timestamp finish_time) {
this.finish_time = finish_time;
}
public Timestamp getStart_time() {
return start_time;
}
public void setStart_time(Timestamp start_time) {
this.start_time = start_time;
}
public Timestamp getUpdata_time() {
return updata_time;
}
public void setUpdata_time(Timestamp updata_time) {
this.updata_time = updata_time;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
}
package com.library.model;
import java.sql.Timestamp;
/**
* 产品分类
* @author Administrator
*
*/
public class ProductTypeModel {
private int id;
private String product_type_name;//产品分类名称
private Timestamp time;//录入时间
private int by_father_type_id;//对应的父类id
private int is_last;//是否最后的子分类:-1不是,1是
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProduct_type_name() {
return product_type_name;
}
public void setProduct_type_name(String product_type_name) {
this.product_type_name = product_type_name;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public void setBy_father_type_id(int by_father_type_id) {
this.by_father_type_id = by_father_type_id;
}
public int getBy_father_type_id() {
return by_father_type_id;
}
public void setIs_last(int is_last) {
this.is_last = is_last;
}
public int getIs_last() {
return is_last;
}
}
package com.library.model;
public class SegmentModel {
private Integer id;
private String operator;
private String phoneThree;
private Integer paygoId;
private String createdate;
private String seRemark;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator == null ? null : operator.trim();
}
public String getPhoneThree() {
return phoneThree;
}
public void setPhoneThree(String phoneThree) {
this.phoneThree = phoneThree == null ? null : phoneThree.trim();
}
public Integer getPaygoId() {
return paygoId;
}
public void setPaygoId(Integer paygoId) {
this.paygoId = paygoId;
}
public String getCreatedate() {
return createdate;
}
public void setCreatedate(String createdate) {
this.createdate = createdate == null ? null : createdate.trim();
}
public String getSeRemark() {
return seRemark;
}
public void setSeRemark(String seRemark) {
this.seRemark = seRemark == null ? null : seRemark.trim();
}
}
\ No newline at end of file
package com.library.model;
import java.sql.Timestamp;
/**
* 会员余额记录
* @author Administrator
*
*/
public class UserBalanceRecordModel {
private int id;
private int by_userid;//对应会员id
private int state;//状态:1充值,2消费
private double price;//金额
private double after_balance;//操作之后的金额
private Timestamp time;//时间
private Timestamp recharge_time;// 充值时间(付款时间)
private int recharge_method;// 支付方式:1:微信支付 2:支付宝支付
private int recharge_state;// 充值状态:1待付款,2已付款
private String recharge_num;// 充值单号,当state=1时候
private String remark;//备注
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBy_userid() {
return by_userid;
}
public void setBy_userid(int by_userid) {
this.by_userid = by_userid;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getAfter_balance() {
return after_balance;
}
public void setAfter_balance(double after_balance) {
this.after_balance = after_balance;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public Timestamp getRecharge_time() {
return recharge_time;
}
public void setRecharge_time(Timestamp recharge_time) {
this.recharge_time = recharge_time;
}
public int getRecharge_state() {
return recharge_state;
}
public void setRecharge_state(int recharge_state) {
this.recharge_state = recharge_state;
}
public String getRecharge_num() {
return recharge_num;
}
public void setRecharge_num(String recharge_num) {
this.recharge_num = recharge_num;
}
public int getRecharge_method() {
return recharge_method;
}
public void setRecharge_method(int recharge_method) {
this.recharge_method = recharge_method;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getRemark() {
return remark;
}
}
package com.library.model;
import com.google.gson.annotations.SerializedName;
import java.sql.Timestamp;
/**
* 会员表
*
* @author Administrator
*/
public class UserModel {
private int id;
private String openid_wx;//微信openid
private double balance;//会员余额
private String nickname;//昵称
private String phone;//手机
private Timestamp time;//注册时间
private String password;//登录密码
private String user_image;//头像
private int user_state;//是否为超级会员(是:8088,否0)
private String vpay_name;//vpay的名称
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOpenid_wx() {
return openid_wx;
}
public void setOpenid_wx(String openid_wx) {
this.openid_wx = openid_wx;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUser_image() {
return user_image;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getVpay_name() {
return vpay_name;
}
public void setVpay_name(String vpay_name) {
this.vpay_name = vpay_name;
}
public int getUser_state() {
return user_state;
}
public void setUser_state(int user_state) {
this.user_state = user_state;
}
}
package com.library.model;
import java.sql.Timestamp;
/**
* 访问日志表
*/
public class VisitLogModel {
private int id;//
private int type;//1管理员接口访问日志,2普通会员访问接口日志
private int by_id;// 对应的表id
private String visit_address;// 访问的地址
private String visit_parm;//访问参数
private String visit_desc;//描述
private Timestamp time;//时间
private String ip_addres;// 请求的ip地址
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getBy_id() {
return by_id;
}
public void setBy_id(int by_id) {
this.by_id = by_id;
}
public String getVisit_address() {
return visit_address;
}
public void setVisit_address(String visit_address) {
this.visit_address = visit_address;
}
public String getVisit_parm() {
return visit_parm;
}
public void setVisit_parm(String visit_parm) {
this.visit_parm = visit_parm;
}
public String getVisit_desc() {
return visit_desc;
}
public void setVisit_desc(String visit_desc) {
this.visit_desc = visit_desc;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
public String getIp_addres() {
return ip_addres;
}
public void setIp_addres(String ip_addres) {
this.ip_addres = ip_addres;
}
}
package com.library.respcode;
/**
* Created by geely
*/
public enum ResponseCode {
SUCCESS(1,"SUCCESS"),//成功
ERROR(-1,"服务器响应失败"),//失败,错误
NEED_LOGIN(2001,"需要登录"),//没有登录
No_Permissions(2002,"没权限"),//没权限
ILLEGAL_ARGUMENT(2003,"不合法参数"),//参数不正确
BUY_SUCCESS(2004,"商品购买成功"),//商品购买成功(价格为零时)
RepeatParticipationPlan(2005,"您已参与该商品的夺宝计划,请不要重复操作"),//重复参与计划
pleaseFillInTheNicknameOfVpay(2006,"个人信息中,请填写vpay的昵称"),//无vpay昵称
ExistingAddress(2007,"已存在地址,不可再添加"),//现在做成只能有一个收货地址
InsufficientBalance(2008,"余额不足"),//余额不足
MorePurchasesThanTheRest(2009,"本次购买的次数不能大于剩余次数");//购买次数多过剩余的
private final int code;
private final String desc;
ResponseCode(int code,String desc){
this.code = code;
this.desc = desc;
}
public int getCode(){
return code;
}
public String getDesc(){
return desc;
}
}
package com.library.respcode;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import java.io.Serializable;
/**
* Created by geely
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
//保证序列化json的时候,如果是null的对象,key也会消失
public class ServerResponse<T> implements Serializable {
private int status;
private String msg;
private T data;
private ServerResponse(int status){
this.status = status;
}
private ServerResponse(int status,T data){
this.status = status;
this.data = data;
}
private ServerResponse(int status,String msg,T data){
this.status = status;
this.msg = msg;
this.data = data;
}
private ServerResponse(int status,String msg){
this.status = status;
this.msg = msg;
}
@JsonIgnore
//使之不在json序列化结果当中
public boolean isSuccess(){
return this.status == ResponseCode.SUCCESS.getCode();
}
public int getStatus(){
return status;
}
public T getData(){
return data;
}
public String getMsg(){
return msg;
}
public static <T> ServerResponse<T> createBySuccess(){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
}
public static <T> ServerResponse<T> createBySuccessMessage(String msg){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
}
public static <T> ServerResponse<T> createBySuccess(T data){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data);
}
public static <T> ServerResponse<T> createBySuccess(String msg,T data){
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data);
}
public static <T> ServerResponse<T> createByError(){
return new ServerResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
}
public static <T> ServerResponse<T> createByErrorMessage(String errorMessage){
return new ServerResponse<T>(ResponseCode.ERROR.getCode(),errorMessage);
}
public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode,String errorMessage){
return new ServerResponse<T>(errorCode,errorMessage);
}
}
\ No newline at end of file
package com.library.service;
import com.library.respcode.ServerResponse;
import javax.servlet.http.HttpServletResponse;
/**
* 管理员服务接口
* @author Administrator
*
*/
public interface AdminService {
/**
* 管理员-登录&退出&获取信息
*/
public ServerResponse adminOpear();
}
package com.library.service;
import com.library.model.AutomaticQueueModel;
import java.math.BigDecimal;
/**
* Created by Administrator on 2018\11\22 0022.
*/
public interface AutomaticCodeService {
/***
*
* Description:判断是否是中国手机号
* @author feng
* @date 2017年8月28日 下午1:38:49
* @version 1.0
* @param phone
* @return
*/
public boolean isChinaPhone(String phone);
/***
*
* Description:定时器调用,手机话费自动充值处理
* @author feng
* @date 2017年8月28日 上午10:51:35
* @version 1.0
*/
public void automaticForTack();
/***
*
* Description:处理后返回的结果
* @author feng
* @date 2017年8月28日 上午10:53:12
* @version 1.0
* @param early 操作的列表数据
* @param success 成功=true,失败=false
* @param desc 描述 (失败的订单要描述失败的原因)
*/
public void automaticForTackResult(AutomaticQueueModel early, boolean success, String desc);
/***
*
* Description:人工转自动处理
* @author feng
* @date 2017年8月28日 下午3:38:43
* @version 1.0
* @param autoId 后台状态id
* @param phone 手机号
* @param money 金额
* @return
*/
public int artificialToAutomatic(Integer autoId,String phone,BigDecimal money);
}
package com.library.service;
import com.library.respcode.ServerResponse;
/**
* 公共接口
*
* @author Administrator
*/
public interface CommService {
/**
* 充值
* @return
*/
ServerResponse Recharge();
/**
* 登录
* @return
*/
ServerResponse adminLogin();
}
package com.library.service.Impl;
import com.library.config.NameValue;
import com.library.mapper.AdminMapper;
import com.library.mapper.CurrencyMapper;
import com.library.model.*;
import com.library.respcode.ResponseCode;
import com.library.respcode.ServerResponse;
import com.library.service.AdminService;
import com.library.util.PictureCode;
import com.library.util.TransformationTools;
import org.apache.http.util.TextUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@Service
public class AdminServiceImpl implements AdminService {
@Resource
private HttpServletRequest request;
@Resource
private CurrencyMapper currencyMapper;
@Resource
private AdminMapper adminMapper;
@Override
public ServerResponse adminOpear() {
try {
String type = request.getParameter("type");//1登录,2退出登录,3获取管理员信息
if (type.equals("1")) {//
String phone = TransformationTools.TransactSQLInjection(request.getParameter("phone"));
String password = TransformationTools.TransactSQLInjection(request.getParameter("password"));
String code = request.getParameter("code").toLowerCase();
// if (!code.equals(((String) request.getSession().getAttribute("RANDOMVALIDATECODEKEY")).toLowerCase())) {
// return ServerResponse.createByErrorCodeMessage(2006, "验证码错误");
// }
List<Map<String, Object>> list = currencyMapper.FindDataListWhere(NameValue.Table_admin, 0, 1, " where phone='" + phone + "' and password='" + password + "'");
if (list != null && list.size() > 0) {//表示有管理员,登陆成功
AdminModel adminModel = (AdminModel) TransformationTools.ToObjectOne(AdminModel.class, list.get(0));
request.getSession().setAttribute(NameValue.Admin_Session, adminModel);
return ServerResponse.createBySuccess();
} else {//用户账号或者密码错误
return ServerResponse.createByErrorMessage("账号或者密码错误!");
}
} else if (type.equals("2")) {//退出登录
request.getSession().setAttribute(NameValue.Admin_Session, null);
return ServerResponse.createBySuccess();
} else {//获取管理员信息
if (request.getSession().getAttribute(NameValue.Admin_Session) == null) {
return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
}
AdminModel adminModel = (AdminModel) request.getSession().getAttribute(NameValue.Admin_Session);
//获取最新的会员信息
Map<String, Object> mapAdmin = currencyMapper.FindDataById(NameValue.Table_admin, adminModel.getId());
adminModel = (AdminModel) TransformationTools.ToObjectOne(AdminModel.class, mapAdmin);
request.getSession().setAttribute(NameValue.Admin_Session, adminModel);
Map<String, Object> map = new HashMap<String, Object>();
map.put("admin_name", adminModel.getAdmin_name());
map.put("phone", adminModel.getAccount());
return ServerResponse.createBySuccess(map);
}
} catch (Exception e) {
e.printStackTrace();
return ServerResponse.createByError();
}
}
}
package com.library.service.Impl;
import com.google.gson.Gson;
import com.library.config.NameValue;
import com.library.mapper.AutomaticQueueMapper;
import com.library.mapper.CurrencyMapper;
import com.library.model.AutomaticQueueModel;
import com.library.model.OrderLogModel;
import com.library.model.OrderModel;
import com.library.model.SegmentModel;
import com.library.service.AutomaticCodeService;
import com.library.util.Paygo24Utils;
import com.library.util.TransformationTools;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Created by Administrator on 2018\11\22 0022.
*/
@Service
@Transactional
public class AutomaticCodeServiceImpl implements AutomaticCodeService {
@Resource
private AutomaticQueueMapper automaticQueueMapper;
@Resource
private CurrencyMapper currencyMapper;
private static String PREFIX_ZERO = "0";
public static String REGULARLY = "^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\\d{8}$";
@Override
public boolean isChinaPhone(String phone) {
if (StringUtils.isBlank(phone)) {
return false;
}
String removePhone = phone;
if (phone.startsWith(PREFIX_ZERO)) {
removePhone = phone.substring(0, phone.length());
}
// 判断是否是中国手机号
if (Pattern.matches(REGULARLY, removePhone)) {
// 是
return true;
}
return false;
}
//开始自动充值
@Override
public void automaticForTack() {
// 得到最早的一条充值记录
Map<String, Object> map = automaticQueueMapper.selectEarlyOne();
if (map != null) {
// 充值业务状态
boolean success = false;
//自动处理状态说明
String desc = "";
AutomaticQueueModel automaticQueueModel = null;
try {
automaticQueueModel = (AutomaticQueueModel) TransformationTools.ToObjectOne(AutomaticQueueModel.class, map);
// 修改状态
automaticQueueModel.setStatus(1);
currencyMapper.updateTableForMysql(TransformationTools.CreatUpdateMysql(automaticQueueModel, NameValue.Table_automatic_queue, "id", null));
//获取订单信息
Map<String, Object> mapOrder = automaticQueueMapper.selectOrderByNumber(automaticQueueModel.getOrder_num());
OrderModel orderModel = (OrderModel) TransformationTools.ToObjectOne(OrderModel.class, mapOrder);
OrderLogModel orderLogModel = new OrderLogModel();
orderLogModel.setLog_order_number(orderModel.getOrder_number());
orderLogModel.setLog_type(5);
orderLogModel.setTime(new Timestamp(System.currentTimeMillis()));
orderLogModel.setLog_content("自动充值-准备开始充值");
//添加订单操作日志
currencyMapper.AddTableForMysql(TransformationTools.CreatAddMysql(orderLogModel, NameValue.Table_order_log, "id", null));
//去充值
Paygo24Utils paygo = new Paygo24Utils();
String result = paygo.payment(automaticQueueModel.getOrder_phone(), automaticQueueModel.getSegment_id(), automaticQueueModel.getOrder_money());
desc = result;//描述
if (result.equals(Paygo24Utils.SUCCESS)) {
success = true;
} else {
success = false;
}
} catch (Exception e) {
e.printStackTrace();
desc = "System error.";
}
// 自动处理结果
this.automaticForTackResult(automaticQueueModel, success, desc);
}
}
//自动处理结果
@Override
public void automaticForTackResult(AutomaticQueueModel early, boolean success, String desc) {
Timestamp newTime = new Timestamp(System.currentTimeMillis());
if (success) {//充值成功
try {
Map<String, Object> mapOrder = automaticQueueMapper.selectOrderByNumber(early.getOrder_num());
OrderModel orderModel = (OrderModel) TransformationTools.ToObjectOne(OrderModel.class, mapOrder);
orderModel.setState(3);
orderModel.setPaygo_time(newTime);
orderModel.setPaygo_remark(desc);
//更新订单表的状态
currencyMapper.updateTableForMysql(TransformationTools.CreatUpdateMysql(orderModel, NameValue.Table_order, "id", null));
//发送短信通知用户
//添加订单日志
OrderLogModel orderLogModel = new OrderLogModel();
orderLogModel.setLog_order_number(early.getOrder_num());
orderLogModel.setLog_type(3);
orderLogModel.setTime(newTime);
orderLogModel.setLog_content("自动充值-充值成功");
//添加订单操作日志
currencyMapper.AddTableForMysql(TransformationTools.CreatAddMysql(orderLogModel, NameValue.Table_order_log, "id", null));
} catch (Exception e) {
e.printStackTrace();
}
} else {//充值失败,转入人工处理
try {
Map<String, Object> mapOrder = automaticQueueMapper.selectOrderByNumber(early.getOrder_num());
OrderModel orderModel = (OrderModel) TransformationTools.ToObjectOne(OrderModel.class, mapOrder);
orderModel.setState(4);
orderModel.setPaygo_remark(desc + "-处理时间:" + newTime);
//更新订单表的状态
currencyMapper.updateTableForMysql(TransformationTools.CreatUpdateMysql(orderModel, NameValue.Table_order, "id", null));
//添加订单日志
OrderLogModel orderLogModel = new OrderLogModel();
orderLogModel.setLog_order_number(early.getOrder_num());
orderLogModel.setLog_type(4);
orderLogModel.setTime(newTime);
orderLogModel.setLog_content("充值失败,转入人工处理-"+desc);
//添加订单操作日志
currencyMapper.AddTableForMysql(TransformationTools.CreatAddMysql(orderLogModel, NameValue.Table_order_log, "id", null));
// early.setStatus(-1);
// currencyMapper.updateTableForMysql(TransformationTools.CreatUpdateMysql(early,NameValue.Table_automatic_queue,"id",null));
} catch (Exception e) {
e.printStackTrace();
}
}
//移除自动充值队列中
currencyMapper.DeleteDataById(NameValue.Table_automatic_queue,early.getId());
}
@Override
public int artificialToAutomatic(Integer autoId, String phone, BigDecimal money) {
return 0;
}
}
package com.library.service.Impl;
import com.library.config.NameValue;
import com.library.mapper.CommMapper;
import com.library.mapper.CurrencyMapper;
import com.library.model.AdminModel;
import com.library.model.UserModel;
import com.library.respcode.ServerResponse;
import com.library.service.AutomaticCodeService;
import com.library.service.CommService;
import com.library.util.MSMmethodUtil;
import com.library.util.Paygo24Utils;
import com.library.util.TransformationTools;
import com.wechat.pay.MD5Util;
import com.wechat.pay.WeChatManager;
import com.wechat.pay.WeChatManager.UserInfo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class CommServiceImpl implements CommService {
@Resource
private HttpServletRequest request;
@Resource
private CommMapper commMapper;
@Resource
private CurrencyMapper currencyMapper;
@Resource
private AutomaticCodeService automaticCodeService;
@Override
public ServerResponse Recharge() {
try {
// String phone = request.getParameter("phone");
// int serviceId = Integer.parseInt(request.getParameter("serviceId"));
// automaticCodeService.automaticForTack();
// Paygo24Utils paygo24Utils = new Paygo24Utils();
// System.out.println("===================开始==================");
// String result = paygo24Utils.payment(phone, serviceId, new BigDecimal(1.0));
// System.out.println(result);
return ServerResponse.createBySuccess();
} catch (Exception e) {
e.printStackTrace();
return ServerResponse.createByError();
}
}
@Override
public ServerResponse adminLogin() {
try {
String phone = TransformationTools.TransactSQLInjection(request.getParameter("account"));//手机号码(type=1,2)
String password = TransformationTools.TransactSQLInjection(request.getParameter("password"));//密码(type=2)
// if (phone.length() < 6) {
// return ServerResponse.createByErrorMessage("账户或者密码错误!");
// }
String new_password = MD5Util.MD5Encode(MD5Util.MD5Encode(password, null), null);
List<Map<String, Object>> list = currencyMapper.FindDataListWhere(NameValue.Table_admin, 0, 1,
" where account = '" + phone + "' and password ='" + new_password + "'");
if (list != null && list.size() > 0) {//登陆账户
AdminModel adminModel = (AdminModel) TransformationTools.ToObjectOne(UserModel.class, list.get(0));
request.getSession().setAttribute(NameValue.Admin_Session, adminModel);
return ServerResponse.createBySuccess();
} else {//账户或者密码错误
return ServerResponse.createByErrorMessage("账户或者密码错误!");
}
} catch (Exception e) {
e.printStackTrace();
return ServerResponse.createByError();
}
}
}
package com.library.test;
import com.library.util.ClientInternet;
import com.library.util.Tools;
import com.wechat.pay.WeChatManager;
public class TTTTTTTTTT {
public static void main(String[] args) {
// SettingCatelog();
String con=WeChatManager.ShortUrl("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb8fe9657eb40e99f&redirect_uri=http%3a%2f%2fsziit.cn.com%2fFirstService%2fUserController%2fwechat_LoginRegist.do&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect");
//{"errcode":0,"errmsg":"ok","short_url":"http:\/\/w.url.cn\/s\/ATdm0Jn"}
System.out.println(con);
}
/**
* 使用模板发送信息给用户
*/
public static void SendTemplate(){
String access_token="nUiX4WS-A49aIBphYvi7ajOfaR5cg5WQbLBCIbkzA1wa2-lRRJMFF67WrFuCmN-LsB43GLdI2s2Oq9EUMzRcV_16hyEsFwyplqB9_AMx_boIOSdAJAQWA";
String urlConnect="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
String touser_OPENID="oFLvmwwNe0AqRF1T8vTCmrhzt_fk";//用户的ID
String template_id="m1nvLL2f70mXksKY3-5EhG5oXfumno-_pyTtTHkO7hQ";//模板ID
String url="https://www.baidu.com/";//点击后跳转的地址
String first="新英雄出场了";//
String keyword1="乐享英雄推送";//
String keyword2="瑞雯已死,取代它的是谁呢!";//
String keyword3="2015-08-21 11:00";//
String keyword4="2015-08-21 11:00";//
String remark="记得去看看喔!(取消本类型消息订阅,请到个人中心!)";//
String json=CreatJSON(touser_OPENID, template_id, url, first, keyword1, keyword2, keyword3, keyword4,remark);
String res=ClientInternet.OpearConnect(urlConnect, null, json);
System.out.println(res);
}
/**
* 组成模板的JSON数据
*/
public static String CreatJSON(String touser_OPENID,String template_id,String url,String first,String keyword1,String keyword2,String keyword3,String keyword4,String remark){
return "{\"touser\":\""+touser_OPENID+"\", \"template_id\":\""+template_id+"\",\"url\":\""+url+"\","+
"\"data\":{\"first\": {\"value\":\""+first+"\",\"color\":\"#173177\"},\"keyword1\":{\"value\":\""+keyword1+"\", \"color\":\"#173177\"},"+
"\"keyword2\": {\"value\":\""+keyword2+"\",\"color\":\"#173177\"},\"keyword3\": {\"value\":\""+keyword3+"\",\"color\":\"#173177\"},"+
"\"keyword4\": {\"value\":\""+keyword4+"\",\"color\":\"#173177\"},"+
"\"remark\":{\"value\":\""+remark+"\",\"color\":\"#173177\"}}}";
}
/**
* 微信公众号的菜单
*/
public static void SettingCatelog(){
String ACCESS_TOKEN="lhwHmctlDHr0eRmK5FJKlWJBCTzXgxpM1_otJ6W6TZSsqcOyaEa83ttcj1s3RPe2UbKEzgDC3jWi2F1q8wJ7fX7HQlqs7Nb96dm3Sh1U6MWjHkQyrYAu5d2_Idh97yN4GYQfABAOGY";
String address="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+WeChatManager.GetAccess_token();
String url=Tools.getAddress("go3");//我的
String about=Tools.getAddress("go4");//关于我们
String http2=Tools.getAddress("go1");//商家
String store1=Tools.getAddress("go2");//地图查看
String recovery1=Tools.getAddress("go6");//首页
String post="{\"button\":[{\"name\":\"汽车服务\", \"sub_button\":["+
"{\"type\":\"view\",\"name\":\"商家\",\"url\":\""+http2+"\" },"+
"{\"type\":\"view\", \"name\":\"首页\",\"url\":\""+recovery1+"\" },"+
"{\"type\":\"view\", \"name\":\"地图查看\",\"url\":\""+store1+"\" }] },"+
"{ \"name\":\"菜单\", \"sub_button\":["+
"{\"type\":\"view\",\"name\":\" 我的\",\"url\":\""+url+"\" },"+
"{\"type\":\"view\", \"name\":\"关于我们\",\"url\":\""+about+"\" }]}]}";
String ress2=ClientInternet.OpearConnect(address, null, post);
System.out.println(ress2);
}
/**
* 获取用户的信息
* {"subscribe":1,"openid":"o5ZsSuBd4skx6-WWOptFnV_yAh0k","nickname":"自由人。","sex":2,"language":"zh_CN","city":"","province":"法兰克福","country":"德国","headimgurl":"http:\/\/wx.qlogo.cn\/mmopen\/PiajxSqBRaELpXUTV9kXUvRux4cqlkFARaibpqp3yfldea0EYaSqibOZrKica06NSsUxbyxEVV5bA5nzjWBIibAL4mQ\/0","subscribe_time":1441625404,"remark":"","groupid":0,"tagid_list":[]}
*/
public static void GetUserInfo(){
String ACCESS_TOKEN="rIUQEOBP1f5Ho43CiC1yO8TPh7JVWFWLrkd9bH537mjc1tuew66s8A_YteHazuBi3xK5ZBS8KWTNa7LLZ1bJmeWWjCqMWOHp3Qo_QYPzHd3KNVKcNY80-m4XYLtf69ZyYMSjADAQEK";
String address="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+ACCESS_TOKEN+"&openid=o5ZsSuBd4skx6-WWOptFnV_yAh0k&lang=zh_CN";
String ress2=ClientInternet.OpearConnect(address, null, "");
System.out.println(ress2);
}
/**
* 批量获取用户openid
"o5ZsSuBd4skx6-WWOptFnV_yAh0k",
"o5ZsSuDdf7qHr5pk7xaPwZpgIO_o",
"o5ZsSuOGwaOLbIylotEJ5AmI7Yro",
"o5ZsSuKrPff8Hz8SvUQEIHQ08sE8",
"o5ZsSuMAI8j_l7h5XR5-VMsdeGa4",
*/
public static void GetUserID(){
String access_token="rIUQEOBP1f5Ho43CiC1yO8TPh7JVWFWLrkd9bH537mjc1tuew66s8A_YteHazuBi3xK5ZBS8KWTNa7LLZ1bJmeWWjCqMWOHp3Qo_QYPzHd3KNVKcNY80-m4XYLtf69ZyYMSjADAQEK";
String address="https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token+"&next_openid=";
String ress2=ClientInternet.OpearConnect(address, null, "");
System.out.println(ress2);
}
/**
* 获得用户的access_token
*{"access_token":"olm2_doKsX5DYZkZaO9cEOu8Gd7JVkp2wLyPW47LHpHrjKIi0pTY1E2Ie14O2BGoXlku2eKw96pcykXYjOflk8VTHqPyeE0m1zPMtWmnD01JfPi8eNfQh0JtO6eHjyVjNHNcAJAVPV","expires_in":7200}
*/
public static void GetAccess_token(){
String address="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxb8fe9657eb40e99f&secret=cf17339fe2c09f8e92bfdcbfb5274042";
String ress2=ClientInternet.OpearConnect(address, null, "");
System.out.println(ress2);
}
}
package com.library.test;
import com.library.util.currency.AESUtils;
import com.library.util.currency.DiscountFileUtils;
import org.tempuri.PayGoService;
import javax.xml.namespace.QName;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
public class Test {
public static void main(String[] args) throws Exception {
Map<String, String> map = DiscountFileUtils.loopRead("/exchangerate.properties");
if (map.get("paygo.pointid") != null && map.get("paygo.password") != null) {
int POINT_ID = Integer.parseInt(map.get("paygo.pointid"));
String PASSWORD = AESUtils.decryptData(AESUtils.DEFAULT_KEY, map.get("paygo.password"));
System.out.println(PASSWORD);
} else {
}
}
}
package com.library.test;
import com.google.gson.Gson;
import com.library.service.Impl.AutomaticCodeServiceImpl;
import com.wechat.pay.MD5Util;
import sun.security.provider.MD5;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.sql.Timestamp;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* Created by Administrator on 2018\10\31 0031.
*/
public class ylmTest {
public static void main(String[] args) {
// String phone="13000000000";
// String password="123";
// String str=MD5Util.MD5Encode(password,null);
// String str2=MD5Util.MD5Encode( phone.substring(0,6)+str,null);
//
// System.out.println(str2);
//
//
System.out.println(System.currentTimeMillis());
System.out.println(new Timestamp(System.currentTimeMillis()));
//
// GregorianCalendar gcal = new GregorianCalendar();
// gcal.setTime(new Date());
// XMLGregorianCalendar xgcal = null;
// try {
// xgcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gcal);
// System.out.println(new Gson().toJson(xgcal));
// System.out.println(xgcal);
// } catch (DatatypeConfigurationException e) {
// e.printStackTrace();
// // Logger.getLogger(Paygo24Utils.class.getName()).log(Level.SEVERE,
// // null, e);
//
// }
}
}
package com.library.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class CharsetFilter implements Filter {
private String enconding;
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
resp.setContentType("text/html;charset="+enconding);
chain.doFilter(new servletreq((HttpServletRequest) req), resp);
// System.out.println("--------");
}
@Override
public void init(FilterConfig con) throws ServletException {
// TODO Auto-generated method stub
enconding=con.getInitParameter("encode") ==null ? "utf-8" :con.getInitParameter("encode");
}
// ����һ���µ�������
class servletreq extends HttpServletRequestWrapper{
private HttpServletRequest request;
private boolean isNotEncode = true;
public servletreq(HttpServletRequest request) {
super(request);
this.request=request;
}
public Map<String, String[]> getParameterMap(){
try {
if(request.getMethod().equals("POST")){
request.setCharacterEncoding(enconding);
return request.getParameterMap();
}else if(request.getMethod().equals("GET")){
Map<String, String[]> map=request.getParameterMap();
if(isNotEncode){
for(Map.Entry<String, String[]> entry: map.entrySet()){
String[] value=entry.getValue();
for(int i=0;i<value.length;i++){
value[i]=new String(value[i].getBytes("iso-8859-1"),"utf-8");
}
}
isNotEncode=false;
}
return map;
}else{
return request.getParameterMap();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String[] getParameterValuse(String name){
return getParameterMap().get(name);
}
public String getParameter(String name){
return getParameterMap().get(name)==null?null:getParameterMap().get(name)[0];
}
}
}
package com.library.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class ClientInternet {
/**维持Session获得sessionid*/
public static String GetCookie(String address) {
String sessionid = address+"?start=yes";
URL url;
try {
url = new URL(address);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// 取得sessionid.
String cookieval = con.getHeaderField("set-cookie");
if (cookieval != null) {
sessionid = cookieval.substring(0, cookieval.indexOf(";"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sessionid;
}
/**向服务器获取路径数据*/
public static String GetData(String address, String sessionid, String list_state) {
String post=("list_state=" + list_state);
return OpearConnect(address, sessionid, post);
}
/**与服务器相连接,参数名称自定(连接地址,SessionId,post参数)*/
public static String OpearConnect(String address, String sessionid, String post){
String urlpath = address;
String path = "";
try {
URL url = new URL(urlpath);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
if (sessionid != null) {
httpcon.setRequestProperty("cookie", sessionid);
}
httpcon.setDoInput(true);
httpcon.setConnectTimeout(50000);
httpcon.setRequestMethod("POST");
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Charset", "UTF-8");
OutputStream out = httpcon.getOutputStream();
if(post!=null){
out.write(post.getBytes("UTF-8"));
}
out.close();
if (httpcon.getResponseCode() == 200) {
InputStreamReader read = new InputStreamReader(httpcon.getInputStream(),"UTF-8");
BufferedReader buffer = new BufferedReader(read);
String instring = null;
while ((instring = buffer.readLine()) != null) {
path += instring;
}
read.close();
httpcon.disconnect();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return path;
}
/**开辟自主线程来进行访问网络*/
public void TheadConnect(String address, String sessionid, String post){
new connect(address, sessionid, post).start();
}
class connect extends Thread{
public String address;
public String sessionid;
public String post;
public int agrs=0;
public connect(String address, String sessionid, String post){
this.address=address;
this.post=post;
this.sessionid=sessionid;
}
public void run() {
String content=OpearConnect(address, sessionid, post);
}
}
/**
* android上传文件到服务器
* @param file 需要上传的文件
* @return 返回上传地址
*/
public static String uploadFile(String address,String sessionid,File file)
{
String result = "";//返回上传地址
String CHARSET = "utf-8"; //设置编码
String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成
String PREFIX = "--" , LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; //内容类型
try {
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (sessionid != null) {
conn.setRequestProperty("cookie", sessionid);
}
conn.setReadTimeout(10*1000);
conn.setConnectTimeout(10*1000);
conn.setDoInput(true); //允许输入流
conn.setDoOutput(true); //允许输出流
conn.setUseCaches(false); //不允许使用缓存
conn.setRequestMethod("POST"); //请求方式
conn.setRequestProperty("Charset", CHARSET); //设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
if(file!=null)
{
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意:
* name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\""+file.getName()+"\""+LINE_END);
sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes("utf-8"));
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while((len=is.read(bytes))!=-1)
{
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功
* 当响应成功,获取响应的流
*/
if (conn.getResponseCode() == 200) {
InputStreamReader read = new InputStreamReader(conn.getInputStream());
BufferedReader buffer = new BufferedReader(read);
String instring = null;
while ((instring = buffer.readLine()) != null) {
result += instring;
}
read.close();
conn.disconnect();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**向服务器发送数据*/
public static String SendData(String address, String sessionid,byte [] data ){
//发送两个参数path state
String urlpath = address;
String path = "";
try {
URL url=new URL(urlpath);
HttpURLConnection httpcon=(HttpURLConnection) url.openConnection();
if(sessionid != null) {
httpcon.setRequestProperty("cookie", sessionid);
}
// httpcon.setDoInput(true);
httpcon.setConnectTimeout(5000);
httpcon.setRequestMethod("POST");
httpcon.setDoOutput(true);
// httpcon.setRequestProperty("Content-Type", "application/octet-stream");
// httpcon.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
httpcon.setRequestProperty("Charset", "UTF-8");
// httpcon.setRequestProperty("Content-Length",String.valueOf(data.length));
OutputStream out=httpcon.getOutputStream();
out.write(data);
out.close();
if(httpcon.getResponseCode()==200){
InputStreamReader read = new InputStreamReader(httpcon.getInputStream(),"UTF-8");
BufferedReader buffer = new BufferedReader(read);
String instring = null;
while ((instring = buffer.readLine()) != null) {
path += instring;
}
read.close();
httpcon.disconnect();
}
return path;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("线程------"+e.toString());
return path;
}
}
/**
* 使用json数据与服务器交互,获取图片 requestMethod默认为POST
*
* @param address 请求地址
* @param requestMethod 请求方法(POST或GET)如需其它方式,请自行修改代码
* @param json 请求的json数据
* @param path 图片存放地址
* @return true 成功;false 失败
* @author xuwenjun
*/
public static boolean OpenConnectForImg(String address, String requestMethod, String json, String path){
String urlpath = address;
try {
URL url = new URL(urlpath);
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.setDoInput(true);
//请求数据为json
httpcon.setRequestProperty("Content-Type", "application/json");
//设置请求超时
httpcon.setConnectTimeout(50000);
//设置requestMethod
if(requestMethod != null)
httpcon.setRequestMethod(requestMethod);
else
httpcon.setRequestMethod("POST");
//若setDoOutput(true),则setRequestMethod将被修改为POST
if(httpcon.getRequestMethod().equals("POST")){
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Charset", "UTF-8");
OutputStream out = httpcon.getOutputStream();
if(json!=null){
out.write(json.getBytes("UTF-8"));
}
out.close();
}else{
httpcon.setDoOutput(false);
httpcon.setRequestProperty("Charset", "UTF-8");
}
//返回结果
if (httpcon.getResponseCode() == 200) {
File file=new File(path);
if(!file.exists()){
file.createNewFile();
}
InputStream read = httpcon.getInputStream();
FileOutputStream fo = new FileOutputStream(file);
byte[] buf = new byte[1024];
int length = 0;
System.out.println("开始下载:" + url);
while ((length = read.read(buf, 0, buf.length)) != -1) {
fo.write(buf, 0, length);
}
read.close();
fo.close();
httpcon.disconnect();
return true;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return false;
}
}
package com.library.util;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import com.google.gson.Gson;
public class GetCityCon {
public static SAXBuilder builder=null;
public static Document document=null;
public static Element root=null;
static{
// File file = new File("C:\\Users\\Administrator\\Desktop\\LocList.xml");
String path=GetCityCon.class.getResource("/").toString();
path=path.substring(6, path.length()-1);
path= URLDecoder.decode(path);
File file = new File(path+"/Com/FS/Util/LocList.xml");
builder = new SAXBuilder();
try {
document = builder.build(file);
root = document.getRootElement();
} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(new Gson().toJson(getAllCountry()));
System.out.println(new Gson().toJson(getProvice("中国")));
System.out.println(new Gson().toJson(getCity("中国", "广东")));
System.out.println(new Gson().toJson(getAddress("中国", "广东", "东莞")));
}
/**
* 获得城市的区
*/
public static List<String> getAddress(String CountryName,String ProviceName,String CityName){
List<String> list=new ArrayList<String>();
// 枚举所有子节点
for (Iterator i = root.getChildren().iterator(); i.hasNext(); ) {
Element el = (Element)i.next();
String name=el.getAttributeValue("Name");
if(name.equals(CountryName)){
for (Iterator j = el.getChildren().iterator(); j.hasNext();) {
Element element2 = (Element)j.next();
name=element2.getAttributeValue("Name");
if(name.equals(ProviceName)){
for (Iterator k = element2.getChildren().iterator(); k.hasNext();) {
Element element3 = (Element)k.next();
name=element3.getAttributeValue("Name");
if(name.equals(CityName)){
for (Iterator l = element3.getChildren().iterator(); l.hasNext();) {
Element element4 = (Element)l.next();
name=element4.getAttributeValue("Name");
list.add(name);
}
break;
}
}
break;
}
}
break;
}
}
return list;
}
/**
* 获得一个省份的所有城市
*/
public static List<String> getCity(String CountryName,String ProviceName){
List<String> list=new ArrayList<String>();
// 枚举所有子节点
for (Iterator i = root.getChildren().iterator(); i.hasNext(); ) {
Element el = (Element)i.next();
String name=el.getAttributeValue("Name");
if(name.equals(CountryName)){
for (Iterator j = el.getChildren().iterator(); j.hasNext();) {
Element element2 = (Element)j.next();
name=element2.getAttributeValue("Name");
if(name.equals(ProviceName)){
for (Iterator k = element2.getChildren().iterator(); k.hasNext();) {
Element element3 = (Element)k.next();
name=element3.getAttributeValue("Name");
list.add(name);
}
break;
}
}
break;
}
}
return list;
}
/**
* 获得某一个国家的所有省份
* @param CountryName
* @return
*/
public static List<String> getProvice(String CountryName){
List<String> list=new ArrayList<String>();
// 枚举所有子节点
for (Iterator i = root.getChildren().iterator(); i.hasNext(); ) {
Element el = (Element)i.next();
String name=el.getAttributeValue("Name");
if(name.equals(CountryName)){
for (Iterator j = el.getChildren().iterator(); j.hasNext();) {
Element element2 = (Element)j.next();
name=element2.getAttributeValue("Name");
list.add(name);
}
break;
}
}
return list;
}
/**
* 获得所有国家
* @return
*/
public static List<String> getAllCountry() {
List<String> list = new ArrayList<String>();
// 枚举所有子节点
for (Iterator i = root.getChildren().iterator(); i.hasNext();) {
Element element = (Element) i.next();
String name = element.getAttributeValue("Name");
list.add(name);
}
return list;
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
package com.library.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import com.google.gson.Gson;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
/**
* 本类和MethodUtil差不多,但本类是MethodUtil的固定方法形态
*
* @author Administrator
*
*/
public class MSMmethodUtil {
public static String appkey = "23767269";
public static String secret = "e58760ff89aa0d55344ce7eff1275506";
public static void main(String[] args) {
// SendSMS("13826834070", "你是傻逼", "乐享电竞");
SendSMSCode("15602901970",Code(), "乐享电竞");
}
/**
* 短信内容:你好,我们有一个通知给你,内容如下:${content},本信息来自${from}
*/
public static void SendSMS(String ToPhone, String Content, String FromName) {
String url = "http://gw.api.taobao.com/router/rest";
TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
// req.setExtend(Code);
req.setSmsType("normal");
req.setSmsFreeSignName("乐享电竞");
req.setRecNum(ToPhone);
req.setSmsTemplateCode("SMS_4270001");
Gson gson = new Gson();
Map<String, String> map = new HashMap<String, String>();
map.put("content", Content);
map.put("from", FromName);
req.setSmsParam(gson.toJson(map, Map.class));// "{\"code\":\"1234\",\"product\":\"三维软件工作室\"}"
AlibabaAliqinFcSmsNumSendResponse response;
try {
response = client.execute(req);
System.out.println(response.getBody());
} catch (ApiException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 发送短信验证码 接收的电话号码,验证码,被注册的名称 短信内容:验证码${code},您正在注册成为${product}用户,感谢您的支持!
*/
public static void SendSMSCode(String ToPhone, String Code, String FromName) {
String url = "http://gw.api.taobao.com/router/rest";
TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
// req.setExtend(Code);
req.setSmsType("normal");
req.setSmsFreeSignName("注册验证");
req.setRecNum(ToPhone);
req.setSmsTemplateCode("SMS_63010252");
Gson gson = new Gson();
Map<String, String> map = new HashMap<String, String>();
map.put("code", Code);
map.put("product", FromName);
req.setSmsParam(gson.toJson(map, Map.class));// "{\"code\":\"1234\",\"product\":\"三维软件工作室\"}"
AlibabaAliqinFcSmsNumSendResponse response;
try {
response = client.execute(req);
System.out.println(response.getBody());
} catch (ApiException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 生成随机的6位数验证码
*/
public static String Code() {
Random random = new Random();
String result = "";
for (int i = 0; i < 6; i++) {
result += random.nextInt(10);
}
System.out.print(result);
return result;
}
}
package com.library.util;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* 生成图片验证码
* @author cyy
*
*/
public class PictureCode {
public static final String RANDOMCODEKEY= "RANDOMVALIDATECODEKEY";//放到session中的key
//private String randString = "0123456789";//随机产生只有数字的字符串 private String
//private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生只有字母的字符串
private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生数字与字母组合的字符串
private int width = 95;// 图片宽
private int height = 25;// 图片高
private int lineSize = 40;// 干扰线数量
private int stringNum = 4;// 随机产生字符数量
private Random random = new Random();
/*
* 获得字体
*/
private Font getFont() {
return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
}
/*
* 获得颜色
*/
private Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc - 16);
int g = fc + random.nextInt(bc - fc - 14);
int b = fc + random.nextInt(bc - fc - 18);
return new Color(r, g, b);
}
/**
* 生成随机图片
*/
public void getRandcode(HttpServletRequest request,
HttpServletResponse response) {
HttpSession session = request.getSession();
// BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,改对象可以在图像上进行各种绘制操作
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
g.setColor(getRandColor(110, 133));
// 绘制干扰线
for (int i = 0; i <= lineSize; i++) {
drowLine(g);
}
// 绘制随机字符
String randomString = "";
for (int i = 1; i <= stringNum; i++) {
randomString = drowString(g, randomString, i);
}
//将生成的随机字符串保存到session中,而jsp界面通过session.getAttribute("RANDOMCODEKEY"),
//获得生成的验证码,然后跟用户输入的进行比较
session.removeAttribute(RANDOMCODEKEY);
session.setAttribute(RANDOMCODEKEY, randomString);
g.dispose();
try {
// 将内存中的图片通过流动形式输出到客户端
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* 绘制字符串
*/
private String drowString(Graphics g, String randomString, int i) {
g.setFont(getFont());
g.setColor(new Color(random.nextInt(101), random.nextInt(111), random
.nextInt(121)));
String rand = String.valueOf(getRandomString(random.nextInt(randString
.length())));
randomString += rand;
g.translate(random.nextInt(3), random.nextInt(3));
g.drawString(rand, 13 * i, 16);
return randomString;
}
/*
* 绘制干扰线
*/
private void drowLine(Graphics g) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(13);
int yl = random.nextInt(15);
g.drawLine(x, y, x + xl, y + yl);
}
/*
* 获取随机的字符
*/
public String getRandomString(int num) {
return String.valueOf(randString.charAt(num));
}
}
\ No newline at end of file
package com.library.util;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import net.sf.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* Description: 保存图片工具类
* Company: youjiang
* @author Kwum
* @date 2016年10月17日 下午5:09:34
* @version 1.0
*/
public class QiniuUtils {
//设置好账号的ACCESS_KEY和SECRET_KEY
// private static String ACCESS_KEY ="5hILYOS8yK0havuWevEe5R3Qh-AUEGwEvLjHvBuH";
private static String ACCESS_KEY = "bJOJLfSclr6-8fSwkkiKioNyKi3qSIoy4JuFH0DB";
private static String SECRET_KEY = "ziEscQ_7iyV95C8M7BrZ0y_2CXyo0hwLSVVYeG_K";
private static String domain = "http://qiniu.xnsystem.com";
//要上传的空间
private static String bucketname = "xntest";
//密钥配置
private static Auth auth ;
//第一种方式: 指定具体的要上传的zone
private static Zone z;
private static Configuration c ;
//创建上传对象
private static UploadManager uploadManager;
private static StringMap policy = new StringMap();
//yipage@163.com
//yipage_wechat
static{
try {
auth = Auth.create(ACCESS_KEY, SECRET_KEY);
long epoch = System.currentTimeMillis()/1000 + 3600;
//3. 构建上传管理对象
policy.put("scope", bucketname);
policy.put("deadline", epoch);
// policy.putNotEmpty("mimeLimit", "image/*");
z = Zone.zone0();
c = new Configuration(z);
uploadManager = new UploadManager(c);
} catch (Exception e) {
e.printStackTrace();
}
}
//简单上传,使用默认策略,只需要设置上传的空间名就可以了
public static String getUpToken() {
long expireSeconds = 36000;
return auth.uploadToken(bucketname, null, expireSeconds, policy);
}
public static String saveImg(HttpServletRequest request,
byte[] file, String fileName) throws IOException {
try {
long name = System.nanoTime();//获取系统当前时间(唯一值)
String ext = fileName.substring(fileName.lastIndexOf("."));
//上传到七牛后保存的文件名
String key = name+ext;
//调用put方法上传
Response res = uploadManager.put(file, key, getUpToken());
//打印返回的信息
JSONObject json = JSONObject.fromObject(res.bodyString());
return json.getString("key");
} catch (QiniuException e) {
Response r = e.response;
// 请求失败时打印的异常的信息
System.out.println(r.toString());
try {
//响应的文本信息
System.out.println(r.bodyString());
} catch (QiniuException e1) {
e1.printStackTrace();
}
}
return "";
}
public static String getPathByUploadImage(HttpServletRequest request,
byte[] file, String fileName)throws Exception{
String imgName = saveImg(request, file, fileName);
String imgPath = "http://"+domain+"/"+imgName;
return imgPath;
}
public static String saveFile(byte[] byteArray,
String fileName) throws IOException {
try {
long name = System.nanoTime();//获取系统当前时间(唯一值)
String ext = fileName.substring(fileName.lastIndexOf("."));
//上传到七牛后保存的文件名
String key = name+ext;
//调用put方法上传
Response res = uploadManager.put(byteArray, key, getUpToken());
//打印返回的信息
JSONObject json = JSONObject.fromObject(res.bodyString());
String imgName = json.getString("key");
//String imgPath = "http://"+domain+"/"+imgName;
return imgName;
} catch (QiniuException e) {
Response r = e.response;
// 请求失败时打印的异常的信息
System.out.println(r.toString());
try {
//响应的文本信息
System.out.println(r.bodyString());
} catch (QiniuException e1) {
//ignore
e1.printStackTrace();
}
}
return "";
}
public static void main(String[] args) {
System.out.println(getUpToken());
}
}
package com.library.util;
import java.util.Date;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmailTools {
//用于给用户发送邮件的邮箱
private static String from = "503781495@qq.com";
//授权码 从QQ上获得
private static String password = "gflhiysqjvwebgfb";
/*
主方法测试用
*/
public static void main(String[] args) {
SendMail("有新下的订单", "aohdoiajdfjasdjf;l", "503781495@qq.com");
}
/**
* 发送邮件
*/
public static void SendMail(String title,String content,String rciveMail) {
try{
Properties prop = new Properties();
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.host", "smtp.qq.com");
prop.setProperty("mail.smtp.auth", "true");
final String smtpPort = "465";
prop.setProperty("mail.smtp.port", smtpPort);
prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.smtp.socketFactory.fallback", "false");
prop.setProperty("mail.smtp.socketFactory.port", smtpPort);
prop.setProperty("mail.debug", "true");
Session session = Session.getDefaultInstance(prop);
session.setDebug(true);
MimeMessage message = createMimeMessage(session, from, rciveMail,title,content);
Transport transport = session.getTransport();
transport.connect( from, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail,String title,String content) throws Exception {
// 1. 创建一封邮件
MimeMessage message = new MimeMessage(session);
// 2. From: 发件人
message.setFrom(new InternetAddress(sendMail, title, "UTF-8"));
// 3. To: 收件人(可以增加多个收件人、抄送、密送)
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "用户名", "UTF-8"));
// 4. Subject: 邮件主题
message.setSubject(title, "UTF-8");
// 5. Content: 邮件正文(可以使用html标签)
message.setContent(content, "text/html;charset=UTF-8");
// 6. 设置发件时间
message.setSentDate(new Date());
// 7. 保存设置
message.saveChanges();
return message;
}
}
package com.library.util;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionCounter implements HttpSessionListener {
public static int activeSessions = 0;
/* Session创建事件 */
public void sessionCreated(HttpSessionEvent event) {
ServletContext ctx = event.getSession().getServletContext();
System.out.println("创建会话");
activeSessions++;
}
/* Session失效事件 */
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext ctx = se.getSession().getServletContext();
System.out.println("注销会话");
activeSessions--;
}
}
\ No newline at end of file
package com.library.util;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.library.mapper.CommMapper;
import com.library.service.AutomaticCodeService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.google.gson.Gson;
/**
* 项目名称:
* 类名: SpringContextUtil
* 描述: 获取bean的工具类,可用于在线程里面获取bean
*/
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext context = null;
@Autowired
private AutomaticCodeService automaticCodeService;
/* (non Javadoc)
* @Title: setApplicationContext
* @Description: spring获取bean工具类
* @param applicationContext
* @throws BeansException
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
System.out.println("========充值系统-开始系统自检=========");
new CheckSystem().start();
this.context = applicationContext;
}
/**
* 进行系统自检
*/
class CheckSystem extends Thread {
int i = 0;
@Override
public void run() {
while (true){
System.out.println("========自检次数:" + i + "=========");
i++;
automaticCodeService.automaticForTack();
try {
sleep(1000 * 5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static <T> T getBean(String beanName) {
return (T) context.getBean(beanName);
}
public static String getMessage(String key) {
return context.getMessage(key, null, Locale.getDefault());
}
public static ApplicationContext getContext() {
return context;
}
}
\ No newline at end of file
package com.library.util;
import java.lang.reflect.Type;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* 工具类
* @author cyy
*
*/
public class Tools {
public static Gson gson=new Gson();
public static Type IntegerListType=new TypeToken<List<Integer>>(){}.getType();
public static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm");
public static SimpleDateFormat format2 = new SimpleDateFormat("yy/MM/dd");
public static SimpleDateFormat format3 = new SimpleDateFormat("yyy-MM-dd hh:mm");
/**
* 保留小数点后两位
*/
public static double SaveTwoPoint(double value){
DecimalFormat df=new DecimalFormat("#.##");
return Double.parseDouble(df.format(value));
}
//获得授权地址
public static String getAddress(String state) {
String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb8fe9657eb40e99f&redirect_uri=http%3a%2f%2fxm-fzw.com%2fUserController%2fwechat_LoginRegist.do&response_type=code&scope=snsapi_userinfo&state="+state+"#wechat_redirect";//首页
return url;
}
//无需授权获得openid
public static String getAddress2(String state) {
String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb8fe9657eb40e99f&redirect_uri=http%3a%2f%2fxm-fzw.com%2fUserController%2fwechat_LoginRegist.do&response_type=code&scope=snsapi_base&state="+state+"#wechat_redirect";//首页
return url;
}
/**
* MD5加密
*/
public static String md5(String password) {
try {
StringBuffer buffer = new StringBuffer();
char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
byte[] bytes = password.getBytes();
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] targ = md.digest(bytes);
for (byte b : targ) {
buffer.append(chars[(b >> 4) & 0x0F]);
buffer.append(chars[b & 0x0F]);
}
return buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.library.util;
import java.io.IOException;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.library.bean.User;
import com.library.config.NameValue;
import com.library.model.AdminModel;
import com.library.respcode.ResponseCode;
import com.library.respcode.ServerResponse;
public class UrlInterceptor implements HandlerInterceptor{
/**
* 该方法也是需要当前对应的Interceptor的preHandle方法的返回值为true时才会执行。该方法将在整个请求完成之后,也就是DispatcherServlet渲染了视图执行,
* 这个方法的主要作用是用于清理资源的,当然这个方法也只能在当前这个Interceptor的preHandle方法的返回值为true时才会执行。
*/
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
/**
* 这个方法只会在当前这个Interceptor的preHandle方法返回值为true的时候才会执行。postHandle是进行处理器拦截用的,它的执行时间是在处理器进行处理之
* 后,也就是在Controller的方法调用之后执行,但是它会在DispatcherServlet进行视图的渲染之前执行,也就是说在这个方法中你可以对ModelAndView进行操
* 作。这个方法的链式结构跟正常访问的方向是相反的,也就是说先声明的Interceptor拦截器该方法反而会后调用,这跟Struts2里面的拦截器的执行过程有点像,
* 只是Struts2里面的intercept方法中要手动的调用ActionInvocation的invoke方法,Struts2中调用ActionInvocation的invoke方法就是调用下一个Interceptor
* 或者是调用action,然后要在Interceptor之前调用的内容都写在调用invoke之前,要在Interceptor之后调用的内容都写在调用invoke方法之后。
*/
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
// TODO Auto-generated method stub
}
/**
* preHandle方法是进行处理器拦截用的,顾名思义,该方法将在Controller处理之前进行调用,SpringMVC中的Interceptor拦截器是链式的,可以同时存在
* 多个Interceptor,然后SpringMVC会根据声明的前后顺序一个接一个的执行,而且所有的Interceptor中的preHandle方法都会在
* Controller方法调用之前调用。SpringMVC的这种Interceptor链式结构也是可以进行中断的,这种中断方式是令preHandle的返
* 回值为false,当preHandle的返回值为false的时候整个请求就结束了。
*/
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp,
Object arg2) throws Exception {
String reqURL=req.getRequestURI();
System.out.println(Tools.format3.format(new Timestamp(System.currentTimeMillis()))+" IP("+req.getRemoteAddr()+")访问的地址:"+reqURL);
if(!CanVisit(reqURL, req, resp)){//判断管理员是否能访问
return false;
}
return true;
// if(!CanVisit(reqURL, req)){//判断用户访问地址是否规范
// //不符合规范访问(用户没有登录)
// resp.getWriter().print("2001");//设置返回代码号
// return false;
// }else{
// // 判断有没有访问权限
// if (DeterMine(reqURL, req)) {// 有
// return true;
// } else {
// // 没有权限
// resp.getWriter().print("2002");// 设置返回代码号
// return false;
// }
// }
}
/**
* 判断该用户是否拥有的访问的权限
* 拥有则返回true,没有返回false
*/
/*public boolean DeterMine(String reqURL,HttpServletRequest req){
//1、得到用户自身拥有的权限,2、判断访问地址是否需要的权限,3、判断是否拥有该权限
User user=(User) req.getSession().getAttribute(NameValue.User_Session);
if(user==null){//还没有登录的用户直接放行
return true;
}
if(user.getManager_not()==1){//是管理员
return true;
}
Integer RootNumber=0;//权限代码号
List<RootBean> list=RootName.GetRootName();
for(int i=0;i<list.size();i++){
RootBean bean=list.get(i);
if(reqURL.indexOf(bean.getUrl())!=-1){//找到地址了
RootNumber=bean.getId();//得到对应的权限代码号
}
}
System.out.println("需要的权限:"+RootNumber);
if(RootNumber==0){//该访问地址不在权限地址之内
return true;
}else{
//从spring里面拿出对象
ServletContext sc = req.getSession().getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
RoleRootDao dao=cxt.getBean(RoleRootDao.class);
Role role=dao.GetOneRole(user.getRole_root());
if(role==null){//查不到角色
return false;
}
List<Integer> root_list=Tools.gson.fromJson(role.getRole_root(), Tools.IntegerListType);
//判断
if(root_list.contains(RootNumber)){//有该权限
return true;
}else{//没有权限
return false;
}
}
}*/
/**
* 判断管理员访问地址是否规范:没有登录的用户不能访问除登录、注册之外的其他地址
* 规范:返回true,不规范:返回false
*/
public boolean CanVisit(String reqURL,HttpServletRequest req, HttpServletResponse resp){
if(reqURL.indexOf("/Admin/")==-1){//不是访问管理接口
return true;
}
AdminModel adminModel=(AdminModel) req.getSession().getAttribute(NameValue.Admin_Session);
if(adminModel==null){//用户没有登录只能访问以下网址
if(reqURL.indexOf("/Admin/admin_login")!=-1){
return true;
}else{//访问其他需要登录
try {
ServerResponse response=ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), ResponseCode.NEED_LOGIN.getDesc());
resp.setContentType("json/text");
resp.getWriter().write(Tools.gson.toJson(response));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
return true;
}
/**
* 判断用户访问地址是否规范:没有登录的用户不能访问除登录、注册之外的其他地址
* 规范:返回true,不规范:返回false
*/
public boolean UserCanVisit(String reqURL,HttpServletRequest req){
User user=(User) req.getSession().getAttribute(NameValue.User_Session);
if(user==null){//用户没有登录只能访问以下网址
if(reqURL.indexOf("User/Regist")!=-1||reqURL.indexOf("User/Login")!=-1
||reqURL.indexOf("/upload_file/")!=-1||reqURL.indexOf("/project_file/")!=-1){
return true;
}else{
return false;
}
}
return true;
}
}
package com.library.util.currency;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.UUID;
public class AESUtils {
private static final String IV_STRING = "16-Bytes--String";
/**
* 默认的密钥
*/
public static final String DEFAULT_KEY = "4be89b269a424036";
/**
* 产生随机密钥(这里产生密钥必须是16位)
*/
public static String generateKey() {
String key = UUID.randomUUID().toString();
key = key.replace("-", "").substring(0, 16);// 替换掉-号
return key;
}
/***
*
* Description:加密
*/
public static String encryptData(String key, String content) {
byte[] encryptedBytes = new byte[0];
try {
byte[] byteContent = content.getBytes("UTF-8");
// 注意,为了能与 iOS 统一
// 这里的 key 不可以使用 KeyGenerator、SecureRandom、SecretKey 生成
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
// 指定加密的算法、工作模式和填充方式
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
encryptedBytes = cipher.doFinal(byteContent);
// 同样对加密后数据进行 base64 编码
return Base64Utils.encode(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/***解密***/
public static String decryptData(String key, String content) throws Exception{
// base64 解码
byte[] encryptedBytes = Base64Utils.decode(content);
byte[] enCodeFormat = key.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES");
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] result = cipher.doFinal(encryptedBytes);
return new String(result, "UTF-8");
}
private static final String encodePass(String pass) {
try {
byte messageDigest[] = null;
MessageDigest digest = MessageDigest
.getInstance("MD5");
digest.update(pass.getBytes());
messageDigest = digest.digest();
pass = Base64.getEncoder().encodeToString(messageDigest);
return pass;
} catch (Exception ex) {
return "";
}
}
public static void main(String[] args) throws Exception {
String data = AESUtils.encryptData(DEFAULT_KEY, "DqwBY/m17AZup5V8SVO3vg==");
String PASSWORD = AESUtils.decryptData(AESUtils.DEFAULT_KEY, "i4pfK2IrI0z7vNlzQMS9MEoa/e8YQomougW3htkq08A=");
System.out.println(data);
System.out.println(PASSWORD);
System.out.println(encodePass("F364ZDrM"));
}
}
package com.library.util.currency;
import java.io.*;
import java.util.Base64;
/** */
/**
* <p>
* BASE64编码解码工具包
* </p>
* <p>
* 依赖javabase64-1.3.1.jar
* </p>
*
* @author jun
* @date 2012-5-19
* @version 1.0
*/
public class Base64Utils {
/** *//**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024;
/** *//**
* <p>
* BASE64字符串解码为二进制数据
* </p>
*
* @param base64
* @return
* @throws Exception
*/
public static byte[] decode(String base64) throws Exception {
return Base64.getDecoder().decode(base64.getBytes());
}
public static String decode(byte[] b){
return new String(Base64.getDecoder().decode(b));
}
/** *//**
* <p>
* 二进制数据编码为BASE64字符串
* </p>
*
* @param bytes
* @return
* @throws Exception
*/
public static String encode(byte[] bytes) throws Exception {
return new String(Base64.getEncoder().encode(bytes));
}
/** *//**
* <p>
* 将文件编码为BASE64字符串
* </p>
* <p>
* 大文件慎用,可能会导致内存溢出
* </p>
*
* @param filePath 文件绝对路径
* @return
* @throws Exception
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
}
/** *//**
* <p>
* BASE64字符串转回文件
* </p>
*
* @param filePath 文件绝对路径
* @param base64 编码字符串
* @throws Exception
*/
public static void decodeToFile(String filePath, String base64) throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
}
/** *//**
* <p>
* 文件转换为二进制数组
* </p>
*
* @param filePath 文件路径
* @return
* @throws Exception
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
}
/** *//**
* <p>
* 二进制数据写文件
* </p>
*
* @param bytes 二进制数据
* @param filePath 文件生成目录
*/
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
InputStream in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
OutputStream out = new FileOutputStream(destFile);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
}
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment