From 4e1dece45363491ebd62b18c48b326220ba6c056 Mon Sep 17 00:00:00 2001 From: admin <1782158860@qq.com> Date: Tue, 13 Sep 2022 16:43:11 +0800 Subject: [PATCH] =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .classpath | 19 + .project | 46 + .settings/.jsdtscope | 12 + .settings/com.genuitec.eclipse.core.prefs | 3 + .../com.genuitec.eclipse.j2eedt.core.prefs | 2 + .settings/org.eclipse.jdt.core.prefs | 7 + .settings/org.eclipse.wst.common.component | 8 + ....eclipse.wst.common.project.facet.core.xml | 11 + ...rg.eclipse.wst.jsdt.ui.superType.container | 1 + .../org.eclipse.wst.jsdt.ui.superType.name | 1 + WebRoot/META-INF/MANIFEST.MF | 3 + .../WEB-INF/classes/applicationContext.xml | 21 + WebRoot/WEB-INF/classes/config.properties | 2 + WebRoot/WEB-INF/classes/springmvc-servlet.xml | 57 + WebRoot/WEB-INF/web.xml | 47 + WebRoot/index.html | 113 ++ src/applicationContext.xml | 21 + src/config.properties | 2 + .../pay/interceptor/testInterceptor.java | 82 ++ src/sc545/pay/main/MainController.java | 140 ++ src/sc545/pay/main/core.java | 161 +++ src/sc545/pay/utils/DBUtil.java | 274 ++++ src/sc545/pay/utils/FileUtils.java | 1100 +++++++++++++++ src/sc545/pay/utils/GsonUtils.java | 140 ++ src/sc545/pay/utils/HttpUtils.java | 602 +++++++++ src/sc545/pay/utils/ImgUtils.java | 244 ++++ src/sc545/pay/utils/MailUtils.java | 85 ++ src/sc545/pay/utils/ReadTxt.java | 716 ++++++++++ src/sc545/pay/utils/Utils.java | 1194 +++++++++++++++++ src/springmvc-servlet.xml | 57 + 30 files changed, 5171 insertions(+) create mode 100644 .classpath create mode 100644 .project create mode 100644 .settings/.jsdtscope create mode 100644 .settings/com.genuitec.eclipse.core.prefs create mode 100644 .settings/com.genuitec.eclipse.j2eedt.core.prefs create mode 100644 .settings/org.eclipse.jdt.core.prefs create mode 100644 .settings/org.eclipse.wst.common.component create mode 100644 .settings/org.eclipse.wst.common.project.facet.core.xml create mode 100644 .settings/org.eclipse.wst.jsdt.ui.superType.container create mode 100644 .settings/org.eclipse.wst.jsdt.ui.superType.name create mode 100644 WebRoot/META-INF/MANIFEST.MF create mode 100644 WebRoot/WEB-INF/classes/applicationContext.xml create mode 100644 WebRoot/WEB-INF/classes/config.properties create mode 100644 WebRoot/WEB-INF/classes/springmvc-servlet.xml create mode 100644 WebRoot/WEB-INF/web.xml create mode 100644 WebRoot/index.html create mode 100644 src/applicationContext.xml create mode 100644 src/config.properties create mode 100644 src/sc545/pay/interceptor/testInterceptor.java create mode 100644 src/sc545/pay/main/MainController.java create mode 100644 src/sc545/pay/main/core.java create mode 100644 src/sc545/pay/utils/DBUtil.java create mode 100644 src/sc545/pay/utils/FileUtils.java create mode 100644 src/sc545/pay/utils/GsonUtils.java create mode 100644 src/sc545/pay/utils/HttpUtils.java create mode 100644 src/sc545/pay/utils/ImgUtils.java create mode 100644 src/sc545/pay/utils/MailUtils.java create mode 100644 src/sc545/pay/utils/ReadTxt.java create mode 100644 src/sc545/pay/utils/Utils.java create mode 100644 src/springmvc-servlet.xml diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..e3afd6f --- /dev/null +++ b/.classpath @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..572c742 --- /dev/null +++ b/.project @@ -0,0 +1,46 @@ + + + pay + + + + + + org.eclipse.wst.jsdt.core.javascriptValidator + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.wst.common.project.facet.core.builder + + + + + org.eclipse.wst.validation.validationbuilder + + + + + com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator + + + + + com.genuitec.eclipse.ast.deploy.core.DeploymentBuilder + + + + + + org.eclipse.jem.workbench.JavaEMFNature + org.eclipse.wst.common.modulecore.ModuleCoreNature + org.eclipse.wst.common.project.facet.core.nature + org.eclipse.jdt.core.javanature + org.eclipse.wst.jsdt.core.jsNature + + diff --git a/.settings/.jsdtscope b/.settings/.jsdtscope new file mode 100644 index 0000000..2fc9dba --- /dev/null +++ b/.settings/.jsdtscope @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/.settings/com.genuitec.eclipse.core.prefs b/.settings/com.genuitec.eclipse.core.prefs new file mode 100644 index 0000000..3057485 --- /dev/null +++ b/.settings/com.genuitec.eclipse.core.prefs @@ -0,0 +1,3 @@ +eclipse.preferences.version=1 +validator.Checked=WebRoot/js,WebRoot/index.html +validator.Unchecked= diff --git a/.settings/com.genuitec.eclipse.j2eedt.core.prefs b/.settings/com.genuitec.eclipse.j2eedt.core.prefs new file mode 100644 index 0000000..7132d6d --- /dev/null +++ b/.settings/com.genuitec.eclipse.j2eedt.core.prefs @@ -0,0 +1,2 @@ +defaultTldInfo=f\=http\://java.sun.com/jsf/core;http\://java.sun.com/jsf/html\=h;http\://struts.apache.org/tags-bean\=bean;http\://java.sun.com/jsp/jstl/fmt\=fmt;bean\=http\://struts.apache.org/tags-bean;nested\=http\://struts.apache.org/tags-nested;http\://java.sun.com/jsp/jstl/sql\=sql;c\=http\://java.sun.com/jsp/jstl/core;fmt\=http\://java.sun.com/jsp/jstl/fmt;http\://struts.apache.org/tags-logic\=logic;http\://java.sun.com/jsp/jstl/xml\=x;http\://java.sun.com/jsp/jstl/core\=c;logic\=http\://struts.apache.org/tags-logic;h\=http\://java.sun.com/jsf/html;http\://struts.apache.org/tags-tiles\=tiles;http\://java.sun.com/jsp/jstl/functions\=fn;tiles\=http\://struts.apache.org/tags-tiles;sql\=http\://java.sun.com/jsp/jstl/sql;http\://struts.apache.org/tags-html\=html;html\=http\://struts.apache.org/tags-html;http\://struts.apache.org/tags-nested\=nested;http\://java.sun.com/jsf/core\=f;fn\=http\://java.sun.com/jsp/jstl/functions;x\=http\://java.sun.com/jsp/jstl/xml +eclipse.preferences.version=1 diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..f42de36 --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.7 diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component new file mode 100644 index 0000000..e97d718 --- /dev/null +++ b/.settings/org.eclipse.wst.common.component @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/.settings/org.eclipse.wst.common.project.facet.core.xml b/.settings/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000..8938ee1 --- /dev/null +++ b/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.container b/.settings/org.eclipse.wst.jsdt.ui.superType.container new file mode 100644 index 0000000..3bd5d0a --- /dev/null +++ b/.settings/org.eclipse.wst.jsdt.ui.superType.container @@ -0,0 +1 @@ +org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/.settings/org.eclipse.wst.jsdt.ui.superType.name b/.settings/org.eclipse.wst.jsdt.ui.superType.name new file mode 100644 index 0000000..05bd71b --- /dev/null +++ b/.settings/org.eclipse.wst.jsdt.ui.superType.name @@ -0,0 +1 @@ +Window \ No newline at end of file diff --git a/WebRoot/META-INF/MANIFEST.MF b/WebRoot/META-INF/MANIFEST.MF new file mode 100644 index 0000000..254272e --- /dev/null +++ b/WebRoot/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/WebRoot/WEB-INF/classes/applicationContext.xml b/WebRoot/WEB-INF/classes/applicationContext.xml new file mode 100644 index 0000000..b102b73 --- /dev/null +++ b/WebRoot/WEB-INF/classes/applicationContext.xml @@ -0,0 +1,21 @@ + + + + + diff --git a/WebRoot/WEB-INF/classes/config.properties b/WebRoot/WEB-INF/classes/config.properties new file mode 100644 index 0000000..20c0243 --- /dev/null +++ b/WebRoot/WEB-INF/classes/config.properties @@ -0,0 +1,2 @@ +a=b +c=d diff --git a/WebRoot/WEB-INF/classes/springmvc-servlet.xml b/WebRoot/WEB-INF/classes/springmvc-servlet.xml new file mode 100644 index 0000000..679c0be --- /dev/null +++ b/WebRoot/WEB-INF/classes/springmvc-servlet.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/WebRoot/WEB-INF/web.xml b/WebRoot/WEB-INF/web.xml new file mode 100644 index 0000000..3339d15 --- /dev/null +++ b/WebRoot/WEB-INF/web.xml @@ -0,0 +1,47 @@ + + + pay + + org.springframework.web.context.ContextLoaderListener + + + + contextConfigLocation + classpath:applicationContext.xml + + + springmvc + org.springframework.web.servlet.DispatcherServlet + + contextConfigLocation + classpath:springmvc-servlet.xml + + + + /index.html + /index.jsp + + + springmvc + / + + + encodingFilter + org.springframework.web.filter.CharacterEncodingFilter + + encoding + UTF-8 + + + forceEncoding + true + + + + encodingFilter + /* + + \ No newline at end of file diff --git a/WebRoot/index.html b/WebRoot/index.html new file mode 100644 index 0000000..9a22d55 --- /dev/null +++ b/WebRoot/index.html @@ -0,0 +1,113 @@ + + + + + + + + 顺诚百宝箱 + + + + + + + +
+ + + + + + + + \ No newline at end of file diff --git a/src/applicationContext.xml b/src/applicationContext.xml new file mode 100644 index 0000000..b102b73 --- /dev/null +++ b/src/applicationContext.xml @@ -0,0 +1,21 @@ + + + + + diff --git a/src/config.properties b/src/config.properties new file mode 100644 index 0000000..20c0243 --- /dev/null +++ b/src/config.properties @@ -0,0 +1,2 @@ +a=b +c=d diff --git a/src/sc545/pay/interceptor/testInterceptor.java b/src/sc545/pay/interceptor/testInterceptor.java new file mode 100644 index 0000000..4d77c25 --- /dev/null +++ b/src/sc545/pay/interceptor/testInterceptor.java @@ -0,0 +1,82 @@ +package sc545.pay.interceptor; + + + +import java.io.PrintWriter; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.*; + +import org.springframework.web.servlet.HandlerInterceptor; + +import sc545.pay.utils.DBUtil; +import sc545.pay.utils.ReadTxt; +import sc545.pay.utils.Utils; + + + + +public class testInterceptor implements HandlerInterceptor{ + + @Override + public boolean preHandle( + HttpServletRequest request, + HttpServletResponse response, + Object handler) throws Exception { + + response.setCharacterEncoding("utf-8"); + response.setContentType("text/html;charset=utf-8"); + request.setCharacterEncoding("utf-8"); + + /*************************************拉黑高频访问ip******************************************/ + if(!"".equals(ReadTxt.getSetting(null, "拉黑ip.txt", Utils.getIpAddr(request), ""))){ + PrintWriter out = response.getWriter(); + out.print("系统检测到高频次访问已被拉黑IP
若误封请前往微信公众号【顺诚百宝箱】反馈
感谢理解!
IP:"+Utils.getIpAddr(request)); + return false; + } + String ipdate = ReadTxt.getSetting(null, "访问者IP.txt", Utils.getIpAddr(request), "");//获取此ip上次访问时间和已经访问的次数 + String[] idt = ipdate.split("_");//分隔 + long i=0;//已经访问的次数 + if(!"".equals(ipdate)){ + if(ipdate.indexOf("_")>0) i=Utils.getNum(idt[1]); + //检查此ip第一次访问到现在过了几秒 + Date ds = Utils.string2Date(idt[0], null); + long xc = (new Date().getTime() - ds.getTime())/1000; + if(xc<=30){//30秒超过50次 + if(i>50){//拉黑此ip3天 + ReadTxt.writeSetting(null,"拉黑ip.txt", Utils.getIpAddr(request), Utils.date2String(new Date(), null)); + ReadTxt.delSetting(null, "访问者IP.txt", Utils.getIpAddr(request)); + }else{//正常ip + } + }else{//正常ip + ReadTxt.delSetting(null, "访问者IP.txt", Utils.getIpAddr(request)); + } + ReadTxt.writeSetting(null,"访问者IP.txt", Utils.getIpAddr(request), idt[0]+"_"+(++i)); + }else + ReadTxt.writeSetting(null,"访问者IP.txt", Utils.getIpAddr(request), Utils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss")+"_1"); + /*******************************************************************************/ + + + + + + DBUtil db = new DBUtil(); + + //闭站 + String cw = ReadTxt.getSetting(null, "setting.ini", "closeweb", "0"); + if("1".equals(cw)) { + String uri = request.getRequestURI(); + if(uri.indexOf("/admin")<0){ + Utils.outHtml(response.getWriter(), ReadTxt.getSetting(null, "setting.ini", "closewebtxt", "本站暂停访问"), "/*about:blank*/"); + return false; + } + } + + + + return true; + } + +} diff --git a/src/sc545/pay/main/MainController.java b/src/sc545/pay/main/MainController.java new file mode 100644 index 0000000..ef5598f --- /dev/null +++ b/src/sc545/pay/main/MainController.java @@ -0,0 +1,140 @@ +package sc545.pay.main; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + + + +import sc545.pay.utils.DBUtil; +import sc545.pay.utils.GsonUtils; +import sc545.pay.utils.Utils; + + + + +@CrossOrigin(origins = "*", maxAge = 3600) +@RestController +public class MainController { + + + /** + * 获取付款码 + * @param param + * @param request + * @param response + * @return + */ + @RequestMapping(value = "/createOrder", produces = "text/html;charset=UTF-8") + public String createOrder( + @RequestParam(required = false, defaultValue = "") String n, + @RequestParam(required = false, defaultValue = "") String t, + HttpServletRequest request, + HttpServletResponse response + ) { + + double num = Utils.getNumDouble(n); + if(num<0.01||num>2000) return "{\"errcode\":\"-1\",\"msg\":\"0<金额<2000\"}"; + core core=new core(); + HashMap order = core.createOrder(num, t); + + return GsonUtils.ObjectToJson(order); + } + + + /** + * 查询订单 + * @param id + * @param request + * @param response + * @return + */ + @RequestMapping(value = "/queryOrder", produces = "text/html;charset=UTF-8") + public String queryOrder( + @RequestParam(required = false, defaultValue = "") String id, + HttpServletRequest request, + HttpServletResponse response + ) { + + + core core=new core(); + Map order = core.queryOrder(id); + + return GsonUtils.ObjectToJson(order); + } + + /** + * 查询支付是否已完成 + * @param id + * @param request + * @param response + * @return + */ + @RequestMapping(value = "/queryPay", produces = "text/html;charset=UTF-8") + public String queryPay( + @RequestParam(required = false, defaultValue = "") String id, + HttpServletRequest request, + HttpServletResponse response + ) { + + + core core=new core(); + Map order = core.queryOrder(id); + + if(order!=null){ + if("3".equals(order.get("ostatus")+"")||"4".equals(order.get("ostatus")+"")) return "{\"msg\":\"已支付\"}"; + else return "{\"msg\":\"未支付\"}"; + }else{ + return "{\"msg\":\"未支付\"}"; + } + } + + /** + * 支付宝通知回调
+ * 设置中的“应用网关” + * @param param + * @param request + * @param response + */ + @RequestMapping(value = "/alinotify", produces = "text/html;charset=UTF-8") + public void alinotify( + @RequestParam(required = false, defaultValue = "") Map param, + HttpServletRequest request, + HttpServletResponse response + ) { + + DBUtil db = new DBUtil(); + core core=new core(); + + //只有支付成功后,支付宝才会回调应用接口,可直接获取支付宝响应的参数 + String order_id = param.get("out_trade_no"); + int s =0; + String ss = param.get("trade_status"); + if("WAIT_BUYER_PAY".equals(ss)) s=1; + else if("TRADE_CLOSED".equals(ss)) s=2; + else if("TRADE_SUCCESS".equals(ss)) s=3; + else if("TRADE_FINISHED".equals(ss)) s=4; + + //检查数据库是否有本数据,有就修改,没有新增 + int i = db.execSql("select * from _orders where out_trade_no = ?", new String[]{order_id}); + if(i>0) core.updateOrder(order_id); + else{ + db.execUpdate("insert into _orders(out_trade_no,trade_no,otitle,onum,ostatus,zfbuser,paynum,getnum,zfbuserid,getbody) " + + "values("+order_id+",?,?,"+param.get("total_amount")+","+s+",?,"+param.get("buyer_pay_amount")+","+param.get("receipt_amount")+",?,?)", new String[]{param.get("trade_no"),param.get("subject"),param.get("buyer_logon_id"),param.get("buyer_id"),param.toString()}); + + } + + + + + } + + +} diff --git a/src/sc545/pay/main/core.java b/src/sc545/pay/main/core.java new file mode 100644 index 0000000..a66657c --- /dev/null +++ b/src/sc545/pay/main/core.java @@ -0,0 +1,161 @@ +package sc545.pay.main; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import sc545.pay.utils.DBUtil; +import sc545.pay.utils.ImgUtils; +import sc545.pay.utils.ReadTxt; +import sc545.pay.utils.Utils; + +import com.alipay.api.AlipayApiException; +import com.alipay.api.AlipayClient; +import com.alipay.api.DefaultAlipayClient; +import com.alipay.api.domain.AlipayTradePrecreateModel; +import com.alipay.api.domain.AlipayTradeQueryModel; +import com.alipay.api.request.AlipayTradePrecreateRequest; +import com.alipay.api.request.AlipayTradeQueryRequest; +import com.alipay.api.response.AlipayTradePrecreateResponse; +import com.alipay.api.response.AlipayTradeQueryResponse; + +public class core { + AlipayClient client = null; + /**支付宝回调的接口地址*/ + private static String aliNotifyUrl = ReadTxt.getSetting(null, "setting.ini", "web", "localhost")+"/pay/alinotify"; + + public core() { + getConfig(); + } + + public static void main(String[] args) { + + //每天定时清空无订单和超时关闭的数据库数据 + core c=new core(); + c.queryOrder("1655263616880"); + c.updateOrder("1655272489467"); + + } + + /** + * 创建付款订单 + */ + public HashMap createOrder(double num,String title){ + if(num<=0) return null; + HashMap rs = new HashMap<>(); + AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest(); + + String h=new Date().getTime()+Utils.randomNum(10, 99)+""; + + AlipayTradePrecreateModel model = new AlipayTradePrecreateModel(); + model.setOutTradeNo(h);//订单号(保证不重复) + model.setTotalAmount(num+"");//订单金额 + model.setSubject(title);//标题(关键字)不可用特殊标点 + model.setQrCodeTimeoutExpress("10m"); + request.setBizModel(model); + request.setNotifyUrl(aliNotifyUrl);//应用网关(异步通知) + + AlipayTradePrecreateResponse response = null; + try { + response = client.execute(request); + } catch (AlipayApiException e) {e.printStackTrace();} + + if(response.isSuccess()){ + + //订单存入数据库 + DBUtil db = new DBUtil(); + int i = db.execUpdate("insert into _orders(out_trade_no,otitle,onum,qrcode) values("+ response.getOutTradeNo()+",?,"+num+",?)", new String[]{title,response.getQrCode()}); + if(i==1){ + rs.put("code", "1"); + rs.put("qrcode", response.getQrCode()); + rs.put("qrimg", ImgUtils.QrImgB64(response.getQrCode(), 300)); + rs.put("out_trade_no", response.getOutTradeNo()); + }else rs.put("errcode", "-1"); + } else { + rs.put("errcode", "-1"); + } + + return rs; + + } + + /**查询订单状态*/ + public Map queryOrder(String orderId){ + if(orderId==null||orderId.trim().length()<1) return null; + DBUtil db = new DBUtil(); + //查数据库 + //先检查数据库是否有这个数据,若查不到或者等待付款,就去更新订单状态,交易成功和交易结束直接返回,订单关闭就把数据库数据删除 + List> rs = db.execQuery("select * from _orders where out_trade_no = ?", new String[]{orderId}); + if(rs!=null&&rs.size()>0){ + Map o = rs.get(0); + if("0".equals(o.get("ostatus")+"")||"1".equals(o.get("ostatus")+"")){ + AlipayTradeQueryResponse r = updateOrder(orderId); + if(r==null) return null; + return queryOrder(orderId); + } + else if("2".equals(o.get("ostatus")+"")) { + db.execUpdate("delete from _orders where out_trade_no = ?", new String[]{orderId}); + return null; + } + + return o; + + }else{ + AlipayTradeQueryResponse r = updateOrder(orderId); + if(r==null) return null; + return queryOrder(orderId); + } + + } + + /**更新订单状态*/ + public AlipayTradeQueryResponse updateOrder(String orderId){ + + if(orderId==null||orderId.trim().length()<1) return null; + DBUtil db = new DBUtil(); + + AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); + AlipayTradeQueryModel model = new AlipayTradeQueryModel(); + model.setOutTradeNo(orderId); + request.setBizModel(model); + AlipayTradeQueryResponse response = null; + try { + response = client.execute(request); + } catch (AlipayApiException e) {e.printStackTrace();} + + int s=0; + if("WAIT_BUYER_PAY".equals( response.getTradeStatus())) s=1; + else if("TRADE_CLOSED".equals( response.getTradeStatus())) s=2; + else if("TRADE_SUCCESS".equals( response.getTradeStatus())) s=3; + else if("TRADE_FINISHED".equals( response.getTradeStatus())) s=4; + + //查询不到说明没有付款 + if(response.getTradeNo()==null||response.getTradeNo().trim().length()<5){ + //db.execUpdate("delete from _orders where out_trade_no = ?", new String[]{orderId}); + return null; + } + //更新数据库订单 + db.execUpdate("update _orders set trade_no=?,ostatus="+s+",zfbuser=?,paynum="+response.getBuyerPayAmount()+",getnum="+response.getReceiptAmount()+",zfbuserid=?,getbody=? where out_trade_no = ?", new String[]{response.getTradeNo(), response.getBuyerLogonId(),response.getBuyerUserId(),response.getBody(),orderId}); + + + return response; + } + + + /** + * 接口调用配置 + */ + public void getConfig() { + + String appid="2021003131621776"; + String private_key="MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCZu1LRuq3Ka79zzv9OgAYNYFVEFetjSsrBJ/N34aBYY3BIOLe5dIt7EQNjx1QUNlSsWU7EwW3AFurXK6iWjXOZrJHZKcM9tzZfsuQeeufnpDtAU90zMSJcu17JfBsTXaXHUEBtQ0wjbuQJ+ihQMB5FtYBg3CuCxUtLqS2/g/n/qlW9ZKPTdnyBCro8pd8w1S5op591aiQGqIZ8ufW45ysCCfjZdOYkFmZMMM2Z5DQjtkQiXgX4aiN5VY5UhyEcGHd3kr9AaYPTC1hLZNUpZXsc2lgdOKQNrZ1FOmxJU4RpNJ9DxrbAgxUQIpvKj5/uOtBFaBmK/CYiVvjBRK5qilZFAgMBAAECggEBAIaNl1pr6wq9re9d4MXDdgilJVwXV1QrtTTEk+t8dsyGFFOSGPRgVmibpnzhjOy39Pp4nGHH7xhutpMn6kIDgoehrHIHhJRy1EuElvc6mdl8PEP8YyIYQjwp3ze4wTX9BElkK0+21GA7Aard4gT1aLmYt8mPSyIFLvcFFz6F8/1ZqKzOtv4jXigXjDzmu/cHks7jamHhknFOn3D7rzfUUViP+2J4HEiSaJXdmzU05aA5glJSLSw4366/GFHsy/Zh3d4FwcFuRu7L+X8gx5vlsPm6E9J7LAt0k+rL5XZVjdkR+Svzkou6EIX+vyZGgxPcUzsZj/V+jMumwALkqyyWP4ECgYEA5wbEJE+sx1NpzeF0/mrIDaB72mX51xpxX93zFCDLzGEY8HiJeR/+UodsNRtGn/W4kBXGSqh0nRnnASs12LGUO+uXcODS2AvSCcV2l5Uh3ecDFavTSeZfAX6yLlw6aecxvRbtDPugPhZ2+i1yc5elyGs5nTd8TjWrdEz0IrTx5eUCgYEAqlmRZpprAb4mSwAQ9+tr9ldvf5xezLzwYNmqRK221OpjFX9oi82MkZrnjcHuEIxpz8quc09A9C+IJ7a1RquWWL52wvjPk52Lbs/vKmGE1h7CF/5Dz4bTOCSF5Kp3SN3HjUI852InWX1pUw1WL5ufVK4mopGs1C3d8ifTSbW9qOECgYEAtO1inMFdIblcqiUAV+NOiwV9GZw1XtVRpu+OV9wbXxNH0cPEffylUwLFpo2W8N0iTo0O/xcQRJytggfSIsNnwMmPj5Iy7YnMU2S2rJ3ZqQwrKUSosz5cdzI+3vnRsXCjTl/vA/ToGNfFE8aV1JsV9XCr7Ukv65wyi2Fc7PViYFUCgYEAoXp+JjDCtsg1LGtHqntzv/RqMSFdi96eTnCGwsuYwIPeoQZBaCTU10FrtijbLryroNmUPKIoBFD6VAsSE4eb4UvK8E9DFb8F6WkaYaZHcWF+w5e3WAWKO3IDqhsdL+lrvC/J49xbSK1lJeFCjaaLho3++aP1nLxN47p0wy6QNoECgYBi5tW50hn9Kyx8WTgJZJgAPT4udLtrLhiLZsS2fucyvumUa5AWUvqF3jAn81ty4hsVXiY5/jiMplRDTCvOSkmmwD+55pSENuVXMDIJXyi9YCB5EJseSr5s5K3IziaVgYkIsiGBz3wVpordQAXID4gm53tWcuoZM7R9d7gwFkhnmQ=="; + String public_key="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsRU1//mlUZ9h0KP1P0ck/y5lPmDUkgNz9fXhZ9QRK2ZlrwnweYC6abOYauy5/Q2yQEjmWO41DfIUEJcejun2yq0hFJ8vz+BiKzEK7jkaHJfm1+MAQ06Y0QzCsPEgTpLiM/wXHvwezqVRjqvlkv6y9K4H0INyWcMi+1BpM0HWdyVeTDxYAG6grn9k6yLfPrqe0zZmVhRUxxQqkf/opZFjRDPQVpsqWU4kICh6/32J83SMPisvdJ7Ad5DJQnGNR/GCQ4tF2rAX/DEi3xuC6+JjIH+CbGYDQq+ovLNXNIS9se80kNRn0ge9guij91u9+JOF/sSMUrf66aUeMS41pZ3+8QIDAQAB"; + String sign_type="RSA2"; + + client =new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appid,private_key,"json","utf-8",public_key,sign_type); + + + } + +} diff --git a/src/sc545/pay/utils/DBUtil.java b/src/sc545/pay/utils/DBUtil.java new file mode 100644 index 0000000..fe2b0cb --- /dev/null +++ b/src/sc545/pay/utils/DBUtil.java @@ -0,0 +1,274 @@ +package sc545.pay.utils; + +import java.lang.reflect.Field; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class DBUtil { + + // 四大金刚 + String driver = "com.mysql.jdbc.Driver";// 驱动名称 + String url = "jdbc:mysql://"+ReadTxt.getSetting(null, "setting.ini", "MySqlIP","127.0.0.1")+":"+ReadTxt.getSetting(null, "setting.ini", "MySqlPort","3306")+"/"+ReadTxt.getSetting(null, "setting.ini", "MySqlName","test")+"?useUnicode=true&characterEncoding=UTF-8&useOldAliasMetadataBehavior=true&autoReconnect=true&useSSL=false";// 连接 + String username = ReadTxt.getSetting(null, "setting.ini", "MySqlUserName","root");// 用户名 + String password = ReadTxt.getSetting(null, "setting.ini", "MySqlPassWord","cheng355217");// 密码 + + // 三剑客 + Connection con = null;// 连接对象 + PreparedStatement pstmt = null;// 语句对象 + ResultSet rs = null;// 结果集对象 + + /** + * 获得连接对象 + * + * @return 连接对象 + * @throws ClassNotFoundException + * @throws SQLException + */ + public Connection getConnection() { + try { + Class.forName(driver); + con = DriverManager.getConnection(url, username, password); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return con; + } + + /** + * 关闭三剑客 + * + * @throws SQLException + */ + public void close(ResultSet rs, PreparedStatement pstmt, Connection con) { + + try { + if (rs != null) + rs.close(); + if (pstmt != null) + pstmt.close(); + if (con != null) + con.close(); + } catch (SQLException e) { + // TODO: handle exception + e.printStackTrace(); + } + } + + /** + * 执行更新 + * + * @param sql + * 传入的预设的 sql语句 + * @param params + * 问号参数列表 + * @return 影响行数 + */ + public int execUpdate(String sql, Object[] params) { + try { + this.getConnection();// 获得连接对象 + this.pstmt = this.con.prepareStatement(sql);// 获得预设语句对象 + + if (params != null) { + // 设置参数列表 + for (int i = 0; i < params.length; i++) { + // 因为问号参数的索引是从1开始,所以是i+1,将所有值都转为字符串形式,好让setObject成功运行 + this.pstmt.setObject(i + 1, params[i] + ""); + } + } + + return this.pstmt.executeUpdate(); // 执行更新,并返回影响行数 + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } finally { + this.close(this.rs, this.pstmt, this.con); + } + return 0; + } + + /** + * 执行查询sql,返回记录条数 + * + * @param sql + * @param params + * @return + */ + public int execSql(String sql, Object[] params) { + try { + this.getConnection();// 获得连接对象 + this.pstmt = this.con.prepareStatement(sql);// 获得预设语句对象 + + if (params != null) { + // 设置参数列表 + for (int i = 0; i < params.length; i++) { + // 因为问号参数的索引是从1开始,所以是i+1,将所有值都转为字符串形式,好让setObject成功运行 + this.pstmt.setObject(i + 1, params[i] + ""); + } + } + int i = 0; + rs = this.pstmt.executeQuery(); + while (rs.next()) { + i++; + } + + return i; // 执行更新,并返回影响行数 + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } finally { + this.close(this.rs, this.pstmt, this.con); + } + return 0; + } + + /** + * 执行查询 + * + * @param sql + * 传入的预设的 sql语句 + * @param params + * 问号参数列表 + * @return 查询后的结果 + */ + public List> execQuery(String sql, Object[] params) { + + try { + this.getConnection();// 获得连接对象 + this.pstmt = this.con.prepareStatement(sql);// 获得预设语句对象 + + if (params != null) { + // 设置参数列表 + for (int i = 0; i < params.length; i++) { + // 因为问号参数的索引是从1开始,所以是i+1,将所有值都转为字符串形式,好让setObject成功运行 + this.pstmt.setObject(i + 1, params[i] + ""); + } + } + + // 执行查询 + ResultSet rs = pstmt.executeQuery(); + + List> al = new ArrayList>(); + + // 获得结果集元数据(元数据就是描述数据的数据,比如把表的列类型列名等作为数据) + ResultSetMetaData rsmd = rs.getMetaData(); + + // 获得列的总数 + int columnCount = rsmd.getColumnCount(); + + // 遍历结果集 + while (rs.next()) { + Map hm = new HashMap(); + for (int i = 0; i < columnCount; i++) { + // 根据列索引取得每一列的列名,索引从1开始 + String columnName = rsmd.getColumnName(i + 1); + // 根据列名获得列值 + Object columnValue = rs.getObject(columnName); + // 将列名作为key,列值作为值,放入 hm中,每个 hm相当于一条记录 + hm.put(columnName, columnValue); + } + // 将每个 hm添加到al中, al相当于是整个表,每个 hm是里面的一条记录 + al.add(hm); + } + + return al; + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } finally { + this.close(this.rs, this.pstmt, this.con); + } + return null; + } + + /** + * 搜索统计 + * + * @param search + * @return + */ + public boolean searchCount(String search) { + String resid = "0"; + List> res = execQuery( + "select id from byx_count where searchstr =?", + new String[] { search }); + if (res != null && res.size() > 0) { + resid = res.get(0).get("id").toString(); + int i = execUpdate( + "update byx_count set countsum = countsum+1 where id = " + + resid, null); + return i > 0 ? true : false; + } else { + int i1 = execUpdate( + "insert into byx_count(countsum,searchstr) values(1,?)", + new String[] { search }); + return i1 > 0 ? true : false; + } + } + + /** + * 获取对象的属性,返回键值对 + * @param obj + * @return + */ + public static HashMap reflect(Object obj) { + if (obj == null) return null; + + Field[] fields = obj.getClass().getDeclaredFields(); + String name=""; + Object[] value=new Object[fields.length]; + + for (int j = 0; j < fields.length; j++) { + fields[j].setAccessible(true); + + // 字段名 + name+="`"+fields[j].getName() + "`,"; + + // 字段值 + if (fields[j].getType().getName().equals(java.lang.String.class.getName())) {//String + + try { + value[j]=(fields[j].get(obj)); + } catch (Exception e) {e.printStackTrace(); + } + + } else if (fields[j].getType().getName().equals(java.lang.Long.class.getName()) || fields[j].getType().getName().equals("long")) {//int/long + + try { + value[j]=(fields[j].getLong(obj)); + } catch (Exception e) {e.printStackTrace();} + + }else if (fields[j].getType().getName().equals(java.lang.Float.class.getName()) || fields[j].getType().getName().equals("float")) {//float/double + + try { + value[j]=(fields[j].getFloat(obj)); + } catch (Exception e) {e.printStackTrace();} + + }else{// 其他类型。。。 + + try { + value[j]=(fields[j].get(obj)); + } catch (Exception e) {e.printStackTrace();} + + } + + } + HashMap m=new HashMap<>(); + m.put("name", new Object[]{name}); + m.put("value", value); + return m; + } + +} diff --git a/src/sc545/pay/utils/FileUtils.java b/src/sc545/pay/utils/FileUtils.java new file mode 100644 index 0000000..5dc3b86 --- /dev/null +++ b/src/sc545/pay/utils/FileUtils.java @@ -0,0 +1,1100 @@ +package sc545.pay.utils; + +import java.awt.Color; +import java.awt.Font; +import java.awt.image.BufferedImage; +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.URL; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; + +import javax.imageio.ImageIO; +import javax.servlet.ServletContext; + +import net.coobird.thumbnailator.Thumbnails; +import net.coobird.thumbnailator.geometry.Positions; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.io.IOUtils; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; + +import sun.misc.BASE64Encoder; + +import com.freeway.image.combiner.ImageCombiner; +import com.freeway.image.combiner.enums.OutputFormat; +import com.freeway.image.combiner.enums.ZoomMode; +import com.google.zxing.*; +import com.google.zxing.common.BitMatrix; + +public class FileUtils { + + public static void main(String[] args) throws Exception { + System.out.println("/a/b".substring(0, "/a/b".length()-1)); + } + + + + + +public static final int BLACK = 0xFF000000; +public static final int WHITE = 0xFFFFFFFF; +public static BufferedImage toBufferedImage(BitMatrix matrix) { + int width = matrix.getWidth(); + int height = matrix.getHeight(); + BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); + } + } + return image; +} + +private static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { + BufferedImage image = toBufferedImage(matrix); + if (!ImageIO.write(image, format, file)) { + throw new IOException("Could not write an image of format " + format + " to " + file); + } +} + +/** + * 删除二维码白边 + * @param matrix + * @return + */ +public static BitMatrix deleteQRWhite(BitMatrix matrix) { + int[] rec = matrix.getEnclosingRectangle(); + int resWidth = rec[2] + 1; + int resHeight = rec[3] + 1; + + BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); + resMatrix.clear(); + for (int i = 0; i < resWidth; i++) { + for (int j = 0; j < resHeight; j++) { + if (matrix.get(i + rec[0], j + rec[1])) + resMatrix.set(i, j); + } + } + return resMatrix; +} + + + +/** + * 生成一张二维码图片文件 + * @param content 二维码内容 + * @param widthHeight 宽高度 + * @param path 图片存储路径(不带文件名) + * @return + */ +public static String QrImgFile(String content,int widthHeight,String path) { + try { + String codeName = UUID.randomUUID().toString();// 二维码的图片名 + String imageType = "jpg";// 图片类型 + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + Map hints = new HashMap(); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints); + bitMatrix= deleteQRWhite(bitMatrix); + // BufferedImage imgbuf = toBufferedImage(bitMatrix); + File file1 = new File(path, codeName + "." + imageType); + writeToFile(bitMatrix, imageType, file1); + return path+codeName + "." + imageType; + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; +} + + +/** + * 生成一张二维码图片(BufferedImage) + * @param content 二维码内容 + * @param widthHeight 宽高度 + * @return + */ +public static BufferedImage QrImgBuf(String content,int widthHeight) { + try { + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + Map hints = new HashMap(); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints); + bitMatrix= deleteQRWhite(bitMatrix); + BufferedImage imgbuf = toBufferedImage(bitMatrix); + return imgbuf; + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; +} + + +/** + * 生成一张二维码图片(base64)
+ * data:image/jpg;base64,base64_code + * @param content 二维码内容 + * @param widthHeight 宽高度 + * @return + */ +public static String QrImgB64(String content,int widthHeight) { + try { + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + Map hints = new HashMap(); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints); + bitMatrix= deleteQRWhite(bitMatrix); + BufferedImage imgbuf = toBufferedImage(bitMatrix); + ByteArrayOutputStream os = new ByteArrayOutputStream();//新建流。 + ImageIO.write(imgbuf, "jpg", os);//利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。 + byte b[] = os.toByteArray();//从流中获取数据数组。 + String str = new BASE64Encoder().encode(b); + return str; + + } catch (Exception e) { + e.printStackTrace(); + } + + return null; +} + + +/** + * 图片质量压缩 + * @param img 文件流 + * @param quality 压缩质量 0~1/1为最高质量 + * @return + */ +public static BufferedImage rarImgBuf(InputStream img, double quality) { + BufferedImage buf =null; + try { + buf = Thumbnails.of(img).scale(1f).outputQuality(quality).asBufferedImage(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return buf; +} + +/** + * 图片质量压缩 + * @param img 文件地址 + * @param quality 压缩质量 0~1/1为最高质量 + * @return + */ +public static File rarImgFile(File img, double quality) { + File arg0 = img; + try { + Thumbnails.of(img).scale(1f).outputQuality(quality).toFile(arg0); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return arg0; +} + +/** + * 裁剪图片
+ * 从左上角开始裁切
+ * 另存图片保持等比缩放,若填写的高度不符合自动调整为等比例 + * + * @param img 图片文件 + * @param p 裁切位置 Positions.TOP/BOTTOM_LEFT/RIGHT、CENTER + * @param x 裁切x轴范围 + * @param y 裁切y轴范围 + * @param width 另存图片的宽度 + * @param height 另存图片的高度 + * @return + */ +public static File cutImgFile(File img,Positions p,int x,int y,int width,int height) { + File arg0 = img; + try { + Thumbnails.of(img).sourceRegion(p, x, y).size(width, height).keepAspectRatio(true).toFile(arg0); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return arg0; +} + + +/** + * 裁剪图片
+ * 从左上角开始裁切
+ * 另存图片保持等比缩放,若填写的高度不符合自动调整为等比例 + * + * @param img 图片流 + * @param p 裁切位置 Positions.TOP/BOTTOM_LEFT/RIGHT、CENTER + * @param x 裁切x轴范围 + * @param y 裁切y轴范围 + * @param width 另存图片的宽度 + * @param height 另存图片的高度 + * @return + */ +public static BufferedImage cutImgBuf(InputStream img,Positions p,int x,int y,int width,int height) { + BufferedImage buf =null; + try { + buf=Thumbnails.of(img).sourceRegion(p, x, y).size(width, height).keepAspectRatio(true).asBufferedImage(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return buf; +} + + + +/** + * 将图片存放在项目根路径下 + * @param servletContext + * @param file MultipartFile文件 + * @param path 在项目根目录下的存放路径 + * @param towhere 数据库入库格式,格式:表#id#字段 + * @return 图片路径(相对) + */ +public static String putImg(ServletContext servletContext,MultipartFile file,String path,String towhere) { + int maxSize = 1024*1024*2; //上传最大为2MB + if (file==null||file.getSize()>maxSize) { + return "图片最大上传2MB"; + } + + + File targetFile=null; + String realurl="";//返回存储路径 + String rid=""; + String fileName=file.getOriginalFilename();//获取文件名加后缀 + if(fileName.trim().length()<1) return "图片不能为空"; + if(fileName!=null&&fileName!=""){ + String lpath=path; + + if(servletContext==null) + path = "D:/"+(lpath.replaceAll("D:/", "").replaceAll("D://", "").replaceAll("D:", "").replaceAll("c:", ""));//图片存储在C盘下的路径 + else{ + //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 + //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 + //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 + String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://webFile"); + if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); + String np=lpath; + if(lpath.indexOf(":")>0){ + np = lpath.substring(lpath.indexOf(":")+2,lpath.length()); + if(!"/".equals(np.substring(0, 1))) np="/"+np; + }else{ + if(!"/".equals(np.substring(0, 1))) np="/"+np; + } + path = basePath+np; + } + String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀 + if (!(fileF.equals(".jpg") || fileF.equals(".jpeg") || fileF.equals(".png") || fileF.equals(".gif"))) { + return "只能上传jpg,jpeg,png,gif格式图片"; + } + //新的文件名 + fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF; + //获取文件夹路径 + File file1=new File(path); + //如果文件夹不存在则创建 + if(!file1.exists() && !file1.isDirectory()){ + file1.mkdirs(); + } + //将图片存入文件夹 + targetFile = new File(file1, fileName); + + try { + //将上传的文件写到服务器上指定的文件。 + file.transferTo(targetFile); + rarImgFile(targetFile, 0.8f); + //赋予权限 + /*String command = "chmod 775 -R " + targetFile; + Runtime runtime = Runtime.getRuntime(); + Process proc = runtime.exec(command);*/ + //生成文件地址 + + if(servletContext==null) realurl=path+"/"+fileName; + else realurl=ReadTxt.getSetting(null, "setting.ini", "resweb", "")+path+"/"+fileName; + //System.out.println("图片上传成功 \nUrl:"+realurl); + } catch (Exception e) { + e.printStackTrace(); + return "系统异常,图片上传失败"; + } + + /** + * 存储完成之后把信息存到数据库,后续用数据库ID来取用文件 + * + * **/ + DBUtil db = new DBUtil(); + int i = db.execUpdate("insert savefile(realurl) values('"+realurl+"')", null); + if(i>0){ + List> rs = db.execQuery("select * from savefile where realurl='"+realurl+"'", null); + if(rs!=null&&rs.size()>0) rid=rs.get(0).get("id")+""; + } + + //成功/添加图片用处 + if(towhere != null && !"".equals(towhere)) + saveSql(realurl, towhere,fileName); + } + + if(servletContext != null) return "/getFile/"+rid; + else return realurl; +} + +/** + * 将图片存放在项目根路径下(带名称,不含文件格式后缀) + * @param servletContext + * @param file MultipartFile文件 + * @param path 在项目根目录下的存放路径 + * @param towhere 数据库入库格式,格式:表#id#字段 + * @return 图片路径(相对) + */ +public static String putImgAsName(ServletContext servletContext,MultipartFile file,String path,String filename,String towhere) { + int maxSize = 1024*1024*2; //上传最大为2MB + if (file==null||file.getSize()>maxSize) { + return "图片最大上传2MB"; + } + File targetFile=null; + String rid=""; + String realurl="";//返回存储路径 + String fileName=file.getOriginalFilename();//获取文件名加后缀 + if(fileName.trim().length()<1) return "图片不能为空"; + if(fileName!=null&&fileName!=""){ + String lpath=path; + if(servletContext==null) + path = "D:/"+(lpath.replaceAll("D:/", "").replaceAll("D://", "").replaceAll("D:", "").replaceAll("c:", ""));//图片存储在C盘下的路径 + else{ + //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 + //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 + //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 + String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://webFile"); + if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); + String np=lpath; + if(lpath.indexOf(":")>0){ + np = lpath.substring(lpath.indexOf(":")+2,lpath.length()); + if(!"/".equals(np.substring(0, 1))) np="/"+np; + }else{ + if(!"/".equals(np.substring(0, 1))) np="/"+np; + } + path = basePath+np; + } + + String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀 + if (!(fileF.equals(".jpg") || fileF.equals(".jpeg") || fileF.equals(".png") || fileF.equals(".gif"))) { + return "只能上传jpg,jpeg,png,gif格式图片"; + } + //新的文件名 + if(filename!=null&&filename.length()>0) + fileName=filename+fileF; + else + fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF; + //获取文件夹路径 + File file1=new File(path); + //如果文件夹不存在则创建 + if(!file1.exists() && !file1.isDirectory()){ + file1.mkdirs(); + } + //将图片存入文件夹 + targetFile = new File(file1, fileName); + + try { + //将上传的文件写到服务器上指定的文件。 + file.transferTo(targetFile); + rarImgFile(targetFile, 0.8f); + //赋予权限 + /*String command = "chmod 775 -R " + targetFile; + Runtime runtime = Runtime.getRuntime(); + Process proc = runtime.exec(command);*/ + //生成文件地址 + if(servletContext==null) realurl=path+"/"+fileName; + else realurl=ReadTxt.getSetting(null, "setting.ini", "resweb", "")+path+"/"+fileName; + //System.out.println("图片上传成功 \nUrl:"+realurl); + } catch (Exception e) { + e.printStackTrace(); + return "系统异常,图片上传失败"; + } + + /** + * 存储完成之后把信息存到数据库,后续用数据库ID来取用文件 + * + * **/ + DBUtil db = new DBUtil(); + int i = db.execUpdate("insert savefile(realurl) values('"+realurl+"')", null); + if(i>0){ + List> rs = db.execQuery("select * from savefile where realurl='"+realurl+"'", null); + if(rs!=null&&rs.size()>0) rid=rs.get(0).get("id")+""; + } + + //成功/添加图片用处 + if(towhere != null && !"".equals(towhere)) + saveSql(realurl, towhere,fileName); + } + + if(servletContext != null) return "/getFile/"+rid; + else return realurl; +} + + +/** + * 将视频存放在项目根路径下 + * @param servletContext + * @param file MultipartFile文件 + * @param path 在项目根目录下的存放路径 + * @param towhere 数据库入库格式,格式:表#id#字段 + * @return 图片路径(相对) + */ +public static String putVideo(ServletContext servletContext,MultipartFile file,String path,String towhere) { + int maxSize = 1024*1024*10; //上传最大为2MB + if (file==null) { + return ""; + } + if (file.getSize()>maxSize) { + return "视频最大上传10MB"; + } + File targetFile=null; + String rid=""; + String realurl="";//返回存储路径 + String fileName=file.getOriginalFilename();//获取文件名加后缀 + if(fileName.trim().length()<1) return ""; + if(fileName!=null&&fileName!=""){ + String lpath=path; + if(servletContext==null) + path = "D:/"+(lpath.replaceAll("D:/", "").replaceAll("D://", "").replaceAll("D:", "").replaceAll("c:", ""));//图片存储在C盘下的路径 + else{ + + //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 + //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 + //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 + String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://webFile"); + if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); + String np=lpath; + if(lpath.indexOf(":")>0){ + np = lpath.substring(lpath.indexOf(":")+2,lpath.length()); + if(!"/".equals(np.substring(0, 1))) np="/"+np; + }else{ + if(!"/".equals(np.substring(0, 1))) np="/"+np; + } + path = basePath+np; + + } + + String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀 + if (!(fileF.equals(".mp4"))) { + return "只能上传mp4格式视频"; + } + //新的文件名 + fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF; + //获取文件夹路径 + File file1=new File(path); + //如果文件夹不存在则创建 + if(!file1.exists() && !file1.isDirectory()){ + file1.mkdirs(); + } + //将图片存入文件夹 + targetFile = new File(file1, fileName); + + try { + //将上传的文件写到服务器上指定的文件。 + file.transferTo(targetFile); + rarImgFile(targetFile, 0.8f); + //赋予权限 + /*String command = "chmod 775 -R " + targetFile; + Runtime runtime = Runtime.getRuntime(); + Process proc = runtime.exec(command);*/ + //生成文件地址 + if(servletContext==null) realurl=path+"/"+fileName; + else realurl=ReadTxt.getSetting(null, "setting.ini", "resweb", "")+path+"/"+fileName; + //System.out.println("图片上传成功 \nUrl:"+realurl); + } catch (Exception e) { + e.printStackTrace(); + return "系统异常,视频上传失败"; + } + + /** + * 存储完成之后把信息存到数据库,后续用数据库ID来取用文件 + * + * **/ + DBUtil db = new DBUtil(); + int i = db.execUpdate("insert savefile(realurl) values('"+realurl+"')", null); + if(i>0){ + List> rs = db.execQuery("select * from savefile where realurl='"+realurl+"'", null); + if(rs!=null&&rs.size()>0) rid=rs.get(0).get("id")+""; + } + + //成功/添加图片用处 + if(towhere != null && !"".equals(towhere)) + saveSql(realurl, towhere,fileName); + } + + if(servletContext != null) return "/getFile/"+rid; + else return realurl; +} + + + + +/** + * 将文件存放在项目根路径下 + * @param servletContext + * @param file MultipartFile文件 + * @param filename 文件名 不含后缀格式,为空自动生成 + * @param path 在项目根目录下的存放路径 + * @param towhere 数据库入库格式,格式:表#id#字段 + * @return 图片路径(相对) + */ +public static String putFile(ServletContext servletContext,MultipartFile file,String filename,String path,String towhere) { + int maxSize = 1024*1024*10; //上传最大为2MB + if (file==null) { + return ""; + } + if (file.getSize()>maxSize) { + return "文件最大上传20MB"; + } + File targetFile=null; + String rid=""; + String realurl="";//返回存储路径 + String fileName=file.getOriginalFilename();//获取文件名加后缀 + if(fileName.trim().length()<1) return ""; + if(fileName!=null&&fileName!=""){ + String lpath=path; + if(servletContext==null) + path = "D:/"+(lpath.replaceAll("D:/", "").replaceAll("D://", "").replaceAll("D:", "").replaceAll("c:", ""));//图片存储在C盘下的路径 + else{ + //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 + //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 + //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 + String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://webFile"); + if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); + String np=lpath; + if(lpath.indexOf(":")>0){ + np = lpath.substring(lpath.indexOf(":")+2,lpath.length()); + if(!"/".equals(np.substring(0, 1))) np="/"+np; + }else{ + if(!"/".equals(np.substring(0, 1))) np="/"+np; + } + path = basePath+np; + } + + String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀 + + //新的文件名 + if(filename!=null&&filename.length()>0) + fileName=filename+fileF; + else + fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF; + //获取文件夹路径 + File file1=new File(path); + //如果文件夹不存在则创建 + if(!file1.exists() && !file1.isDirectory()){ + file1.mkdirs(); + } + //将图片存入文件夹 + targetFile = new File(file1, fileName); + + try { + //将上传的文件写到服务器上指定的文件。 + file.transferTo(targetFile); + //赋予权限 + /*String command = "chmod 775 -R " + targetFile; + Runtime runtime = Runtime.getRuntime(); + Process proc = runtime.exec(command);*/ + //生成文件地址 + if(servletContext==null) realurl=path+"/"+fileName; + else realurl=ReadTxt.getSetting(null, "setting.ini", "resweb", "")+path+"/"+fileName; + //System.out.println("图片上传成功 \nUrl:"+realurl); + } catch (Exception e) { + e.printStackTrace(); + return "系统异常,视频上传失败"; + } + + /** + * 存储完成之后把信息存到数据库,后续用数据库ID来取用文件 + * + * **/ + DBUtil db = new DBUtil(); + int i = db.execUpdate("insert savefile(realurl) values('"+realurl+"')", null); + if(i>0){ + List> rs = db.execQuery("select * from savefile where realurl='"+realurl+"'", null); + if(rs!=null&&rs.size()>0) rid=rs.get(0).get("id")+""; + } + + //成功/添加图片用处 + if(towhere != null && !"".equals(towhere)) + saveSql(realurl, towhere,fileName); + } + + if(servletContext != null) return "/getFile/"+rid; + else return realurl; +} + + +/** + * 把上传的文件信息存入数据库 + * @param realurl 文件路径 + * @param towhere 数据库入库格式,格式:表#id#字段 + * @param saveName 显示文件名称 + */ +public static void saveSql(String realurl, String towhere, String saveName) { + + if(realurl.indexOf("http")>=0 || realurl.indexOf("upload")<0) return; + + //标记文件被使用的地方,方便后续清理无用文件 + // 标记位置格式:表#id#字段,比如哪个表里哪条数据的哪个字段使用该文件,byx_class#16#clist + DBUtil db = new DBUtil(); + + if(towhere.split("#").length>2&&realurl.trim().length()>0){ + String mstab = towhere.split("#")[0]; + String msid = towhere.split("#")[1]; + String mstag = towhere.split("#")[2]; + + if(realurl.indexOf("/getFile/")==0) { + realurl=realurl.replace("/getFile/", ""); + if(db.execSql("select * from savefile where id = '"+realurl+"'", null)>0){//已存在 + db.execUpdate("update savefile set mstab=?,msid=?,mstag=?,savename=? where id=?", new String[]{mstab.trim(),msid.trim(),mstag.trim(),realurl.trim(),saveName==null?"":saveName.trim()}); + }else{//不存在 + //db.execUpdate("insert into savefile(realurl,mstab,msid,mstag,savename) values(?,?,?,?,?)", new String[]{realurl.trim(),mstab.trim(),msid.trim(),mstag.trim(),saveName==null?"":saveName.trim()}); + } + }else{ + if(db.execSql("select * from savefile where realurl = '"+realurl+"'", null)>0){//已存在 + db.execUpdate("update savefile set mstab=?,msid=?,mstag=?,savename=? where realurl=?", new String[]{mstab.trim(),msid.trim(),mstag.trim(),realurl.trim(),saveName==null?"":saveName.trim()}); + }else{//不存在 + db.execUpdate("insert into savefile(realurl,mstab,msid,mstag,savename) values(?,?,?,?,?)", new String[]{realurl.trim(),mstab.trim(),msid.trim(),mstag.trim(),saveName==null?"":saveName.trim()}); + } + } + + + } + +} + + +/** + * 创建一个文件并写入内容 + * @param servletContext + * @param path 路径(不含文件名) + * @param content 内容 + * @param suffix 后缀名(不含点) + * @param oldfile 自己设定文件名(含后缀) 可带路径,若为空则根据时间戳生成随机文件名 + * @return + */ +public static String writeFile(ServletContext servletContext, String path, + String content, String suffix, String oldfile) { + + if(".".equals(suffix.substring(0, 1))) suffix=suffix.substring(1, suffix.length()); + + //兼容文件名含路径 + if(oldfile!=null&&!"".equals(oldfile.trim())){ + int i = oldfile.replace("\\","/").lastIndexOf("/"); + if(i>0) + path=oldfile.substring(0, i); + oldfile=oldfile.substring(i+1, oldfile.length()); + } + + String path1 = ""; + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + if (servletContext == null) { + if(path.indexOf(":") <= 0&&path.indexOf("/") <0) + path1 = "D:\\" + path; + else path1 = path; + } else { + //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 + //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 + //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 + String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://webFile"); + if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); + String np=path; + if(path.indexOf(":")>0){ + np = path.substring(path.indexOf(":")+2,path.length()); + if(!"/".equals(np.substring(0, 1))) np="/"+np; + }else{ + if(!"/".equals(np.substring(0, 1))) np="/"+np; + } + path1 = basePath+np; + } + + if(!"/".equals(path1.replace("\\", "/").substring(path1.replace("\\", "/").length()-1))) path1+="/"; + File file1 = new File(path1); + if (!file1.exists() && !file1.isDirectory()) { + file1.mkdirs(); + } + + String fileName = new Date().getTime() + "_" + + new Random().nextInt(1000) + "." + suffix; + if(oldfile!=null&&!"".equals(oldfile.trim())) fileName = oldfile; + path1 += fileName; + file1 = new File(path1); + + try { + if (!file1.exists()) { + file1.createNewFile(); + } + PrintWriter out = new PrintWriter( + new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(path1), "UTF-8"))); + out.write(content); + out.flush(); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + return fileName; +} + +/** + * 删除上传的文件,联通表数据一块删除 + *
servletContext为空默认C盘 + */ +public static void delfile(ServletContext servletContext, String path) { + path=path.replace(ReadTxt.getSetting(null, "setting.ini", "resweb", ""),""); + if(path.indexOf("http")==0 || path.indexOf("//")==0) return ; + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + String path1 = ""; + if (servletContext == null) { + if(path.indexOf(":") <= 0) + path1 = "D:\\" + path; + } else { + if(path.indexOf("/getFile/")==0){ + String rid = path.replace("/getFile/", ""); + DBUtil db = new DBUtil(); + List> rs = db.execQuery("select * from savefile where id ="+rid, null); + if(rs!=null&&rs.size()>0){ + path=rs.get(0).get("realurl")+""; + path1=rs.get(0).get("realurl")+""; + } + } else path1 = servletContext.getRealPath(path); + } + + File file1 = new File(path1); + if(file1.exists()) { + file1.delete(); + //兼容 + new DBUtil().execUpdate("delete from savefile where realurl=?", new String[]{path}); + + } + + +} + + +/** + * 删除字符串中提取的文件 + * + * @param path + * 项目根目录下的文件路径(servletContext若null为c盘下的) + */ +public static void delFileForStr(ServletContext servletContext, String str) { + + ArrayList imgs = Utils.getImgStr(str, true); + DBUtil db = new DBUtil(); + + for (String path : imgs) { + path=path.replace(ReadTxt.getSetting(null, "setting.ini", "resweb", ""),""); + if(path.indexOf("http")==0 || path.indexOf("//")==0) continue; + String oldpath = path; + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + path=path.replace(ReadTxt.getSetting(null, "setting.ini", "resweb", ""),""); + + String path1 = ""; + if (servletContext == null) { + if(path.indexOf(":") <= 0) + path1 = "D:\\" + path; + } else { + if(path.indexOf("/getFile/")==0){ + String rid = path.replace("/getFile/", ""); + List> rs = db.execQuery("select * from savefile where id ="+rid, null); + if(rs!=null&&rs.size()>0){ + oldpath=rs.get(0).get("realurl")+""; + path1=rs.get(0).get("realurl")+""; + } + } else path1 = servletContext.getRealPath(path); + } + + File file1 = new File(path1); + if(file1.exists()) { + file1.delete(); + + //兼容img_tag + db.execUpdate("delete from savefile where realurl='"+oldpath+"'", null); + + } + } + + +} + +public static void intoSqlForStr(String str,String towhere,String saveName) { + ArrayList imgs = Utils.getImgStr(str, true); + DBUtil db = new DBUtil(); + String mstab = towhere.split("#")[0]; + String msid = towhere.split("#")[1]; + String mstag=""; + if(towhere.split("#").length>2) + mstag = towhere.split("#")[2]; + + for (String path : imgs) { + if(path.indexOf("/getFile/")==0){ + String rid = path.replace("/getFile/", ""); + List> rs = db.execQuery("select * from savefile where id ="+rid, null); + if(rs!=null&&rs.size()>0){ + path=rs.get(0).get("realurl")+""; + + } + } + + if(path.indexOf("http")>=0 || path.indexOf("upload")<0) continue; + + if(db.execSql("select * from savefile where realurl = '"+path+"'", null)>0){//已存在 + db.execUpdate("update savefile set mstab=?,msid=?,mstag=?,savename=? where realurl=?", new String[]{mstab.trim(),msid.trim(),mstag.trim(),saveName==null?"":saveName.trim(),path.trim()}); + }else{//不存在 + db.execUpdate("insert into savefile(realurl,mstab,msid,mstag,savename) values(?,?,?,?,?)", new String[]{path.trim(),mstab.trim(),msid.trim(),mstag.trim(),saveName==null?"":saveName.trim()}); + } + } + +} + + + +/** + * 下载url图片 + * @param url + * @return + */ +public static File downloadImage(String url) { + File file = null; + + URL urlfile; + InputStream inputStream = null; + OutputStream outputStream= null; + try { + file = File.createTempFile(new Date().getTime()+"_"+new Random().nextInt(1000), url.substring(url.lastIndexOf("."))); + //下载 + urlfile = new URL(url); + inputStream = urlfile.openStream(); + outputStream= new FileOutputStream(file); + + int bytesRead = 0; + byte[] buffer = new byte[8192]; + while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (null != outputStream) { + outputStream.close(); + } + if (null != inputStream) { + inputStream.close(); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + return file; +} + +public static MultipartFile getMultipartFile(File file) { + FileItem item = new DiskFileItemFactory().createItem("file" + , MediaType.MULTIPART_FORM_DATA_VALUE + , true + , file.getName()); + try (InputStream input = new FileInputStream(file); + OutputStream os = item.getOutputStream()) { + // 流转移 + IOUtils.copy(input, os); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid file: " + e, e); + } + + return new CommonsMultipartFile(item); +} + +/** + * 返回文件类型 + * @param file + * @return + */ +public static ResponseEntity returnFile(File file) { + if (file == null) { + return null; + } + HttpHeaders headers = new HttpHeaders(); + headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); + headers.add("Content-Disposition", "attachment; filename=" + file.getName()); + headers.add("Pragma", "no-cache"); + headers.add("Expires", "0"); + headers.add("Last-Modified", new Date().toString()); + headers.add("ETag", String.valueOf(System.currentTimeMillis())); + return ResponseEntity + .ok() + .headers(headers) + .contentLength(file.length()) + .contentType(MediaType.parseMediaType("application/octet-stream")) + .body(new FileSystemResource(file)); +} + + + +/** + * 制作合成图片 +* @param title 课程名称 15字内 + * @param des 课程简介 48字内 + * @param teacher 老师名称 + * @param teacherImgUrl 老师透明照片180*318 + * @param localUrl 二维码地址 + * @return + */ +public String imgPS(String title,String des,String teacher,String teacherImgUrl,String localUrl) { + String r=null; + try { + String bjUrl = "file:///C://webimg/bj.jpg"; + String imgUrl = teacherImgUrl; + + //标题x,y轴,字体大小,最大行数,行高 + int title_x=27; + int title_y=30; + int title_f=100; + int title_h=2; + int title_l=120; + if(title.length()<=6){//6字以内 + title_x=40; + title_y=30; + title_f=100; + title_h=2; + title_l=120; + }else if(title.length()>6&&title.length()<9){ //7-8字 + title_x=22; + title_y=67; + title_f=85; + title_h=2; + title_l=88; + }else if(title.length()>8&&title.length()<13){ //9-12字 + title_x=33; + title_y=32; + title_f=80; + title_h=3; + title_l=85; + }else{ + title_x=27; + title_y=30; + title_f=65; + title_h=3; + title_l=75; + } + + //简介x,y轴,字体大小 + int des_x=27; + int des_y=30; + int des_f=20; + int des_h=2; + int des_l=25; + if(des.length()<=16){//16字以内 + des_y=310; + des_h=1; + }else if(title.length()>16&&title.length()<33){ //16-32字 + des_y=303; + des_h=2; + }else{ //32++ + des_y=290; + des_h=3; + } + + teacher = "主讲人:"+teacher; + //讲师x轴 + int tx = (178-(teacher.length()*24))/2; + + + Color c1=new Color(26, 121, 134); + //合成器(指定背景图和输出格式,整个图片的宽高和相关计算依赖于背景图,所以背景图的大小是个基准) + ImageCombiner combiner = new ImageCombiner( bjUrl, 385, 666, ZoomMode.Height, OutputFormat.JPG); + + //标题 + combiner.addTextElement(title, new Font("微软雅黑",Font.BOLD, title_f), title_x, title_y) //内容,默认字体为阿里普惠,字体大小,x,y + .setCenter(false) //居中绘制(会忽略x坐标,改为自动计算) + .setAlpha(1.0f) //透明度(0.0~1.0) + .setRotate(0) //旋转(0~360) + .setAutoBreakLine(340, title_h, title_l) //自动换行 + .setColor(c1); //颜色 + + //简介 + combiner.addTextElement(des, new Font("微软雅黑",Font.BOLD, des_f), des_x,des_y) //内容,默认字体为阿里普惠,字体大小,x,y + .setCenter(false) //居中绘制(会忽略x坐标,改为自动计算) + .setAutoBreakLine(335, des_h, des_l) //自动换行 /最大宽度,最大行数,行高 + .setColor(c1); //颜色 + + //讲师 + combiner.addTextElement(teacher, new Font("微软雅黑",Font.BOLD, 24), tx+22, 390) //内容,默认字体为阿里普惠,字体大小,x,y + .setCenter(false) //居中绘制(会忽略x坐标,改为自动计算) + .setAlpha(1.0f) //透明度(0.0~1.0) + .setRotate(0) //旋转(0~360) + .setAutoBreakLine(178, 1, 24) //自动换行 /最大宽度,最大行数,行高 + .setColor(Color.WHITE); //颜色 + + //图片 + combiner.addImageElement(imgUrl, 205, 349, 180, 318, ZoomMode.Width) //imgUrl, x, y, width, height, zoomMode + .setCenter(false) //居中绘制(会忽略x坐标,改为自动计算) + .setRoundCorner(0); //设置圆角 + + + //生成二维码Buffer + BufferedImage imgbuf = QrImgBuf(localUrl, 200); + combiner.addImageElement(imgbuf, 29, 441, 165, 165, ZoomMode.WidthHeight) + .setRoundCorner(0);//圆角 + + //执行图片合并 + combiner.combine(); + + //可以获取流(并上传oss等) + //InputStream is = combiner.getCombinedImageStream(); + + //也可以保存到本地 + //combiner.save("D://image.jpg"); + + //压缩图片 + //BufferedImage img = rarImgBuf(combiner.getCombinedImageStream(),0.5f); + + //输出为base64 + byte[] arr = IOUtils.toByteArray(combiner.getCombinedImageStream()); + r = Base64.encodeBase64String(arr);//转换为base64格式 + + } catch (Exception e) { + System.out.println(e); + } + + return r; +} + + + +} diff --git a/src/sc545/pay/utils/GsonUtils.java b/src/sc545/pay/utils/GsonUtils.java new file mode 100644 index 0000000..60821c3 --- /dev/null +++ b/src/sc545/pay/utils/GsonUtils.java @@ -0,0 +1,140 @@ +package sc545.pay.utils; + + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParser; +import com.google.gson.reflect.TypeToken; + +public class GsonUtils{ + + //线程安全的 + private static final Gson GSON; + private static final Gson GSON_NULL; // 不过滤空值 + static { + GSON = new GsonBuilder().enableComplexMapKeySerialization() //当Map的key为复杂对象时,需要开启该方法 +// .serializeNulls() //当字段值为空或null时,依然对该字段进行转换 +// .excludeFieldsWithoutExposeAnnotation()//打开Export注解,但打开了这个注解,副作用,要转换和不转换都要加注解 + .setDateFormat("yyyy-MM-dd HH:mm:ss")//序列化日期格式 "yyyy-MM-dd" +// .setPrettyPrinting() //自动格式化换行 + .disableHtmlEscaping() //防止特殊字符出现乱码 + .create(); + GSON_NULL = new GsonBuilder().enableComplexMapKeySerialization() //当Map的key为复杂对象时,需要开启该方法 + .serializeNulls() //当字段值为空或null时,依然对该字段进行转换 +// .excludeFieldsWithoutExposeAnnotation()//打开Export注解,但打开了这个注解,副作用,要转换和不转换都要加注解 + .setDateFormat("yyyy-MM-dd HH:mm:ss")//序列化日期格式 "yyyy-MM-dd" +// .setPrettyPrinting() //自动格式化换行 + .disableHtmlEscaping() //防止特殊字符出现乱码 + .create(); + } + + //获取gson解析器 + public static Gson getGson() { + return GSON; + } + + //获取gson解析器 有空值 解析 + public static Gson getWriteNullGson() { + return GSON_NULL; + } + + + /** + * 根据对象返回json + */ + public static String ObjectToJson(Object object) { + return GSON.toJson(object); + } + + /** + * 将字符串转化对象 + * + * @param json 源字符串 + * @param classOfT 目标对象类型 + * @param + * @return + */ + public static T JsonToObject(String json, Class classOfT) { + return GSON.fromJson(json, classOfT); + } + + /** + * 将字符串转化对象 + * + * @param json 源字符串 + * @param t 目标对象类型 + * @param + * @return + */ + public static T JsonToObject(String json, Type t) { + return GSON.fromJson(json, t); + } + + /** + * 将json转化为对应的实体对象 + * new TypeToken>() {}.getType() + * new TypeToken>() {}.getType() + * new TypeToken>>() {}.getType() + */ + public static T JsonToBean(String json, Type typeOfT) { + return GSON.fromJson(json, typeOfT); + } + + /** + * 转成list + * @param gsonString + * @param cls + * @return + */ + public static List JsonToList(String gsonString, Class cls) { + return GSON.fromJson(gsonString, new TypeToken>() { + }.getType()); + } + + /** + * 转成list中有map的 + * @param gsonString + * @return + */ + public static List> JsonToListMaps(String gsonString) { + return GSON.fromJson(gsonString, new TypeToken>>() { + }.getType()); + } + + /** + * 转成map + * @param gsonString + * @return + */ + public static Map JsonToMaps(String gsonString) { + return GSON.fromJson(gsonString, new TypeToken>() { + }.getType()); + } + + + + + + + + /** + * 获取json字符串中的某个值 + * @param str json字符串 + * @param key 字段名 + * @param errorKey 若可能返回错误码且没有上述key这个字段,这里写错误码的字段名,否则填null + * @return 若错误码,返回 "_errorKey_错误码字段值" + */ + public static String getJsonValue(String str,String key,String errorKey){ + if(str==null) return ""; + if(errorKey!=null&&str.indexOf(errorKey)>=0) + return "_"+errorKey+"_"+new JsonParser().parse(str).getAsJsonObject().get(errorKey).getAsString(); + else + return new JsonParser().parse(str).getAsJsonObject().get(key).getAsString(); + } + +} diff --git a/src/sc545/pay/utils/HttpUtils.java b/src/sc545/pay/utils/HttpUtils.java new file mode 100644 index 0000000..5bbe9cc --- /dev/null +++ b/src/sc545/pay/utils/HttpUtils.java @@ -0,0 +1,602 @@ +package sc545.pay.utils; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.apache.commons.lang3.StringUtils; +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.ParseException; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.CookieStore; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.TrustStrategy; +import org.apache.http.util.EntityUtils; + + +/** + * 基于 httpclient 4.5版本的 http工具类 + * + * + */ +public class HttpUtils { + + private static final CloseableHttpClient httpClient; + public static final String CHARSET = "UTF-8"; + // 采用静态代码块,初始化超时时间配置,再根据配置生成默认httpClient对象 + static { + //10秒相应超时 + RequestConfig config = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).setConnectionRequestTimeout(5000).build(); + httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build(); + } + + public static String doGet(String url, Map params) { + return doGet(url, params, CHARSET); + } + + public static String doGetSSL(String url, Map params) { + return doGetSSL(url, params, CHARSET); + } + + public static String doPost(String url, Map params){ + return doPost(url, params, CHARSET); + } + + /** + * HTTP Get 获取内容 + * @param url 请求的url地址 ?之前的地址 + * @param params 请求的参数 + * @param charset 编码格式 + * @return 页面内容 + */ + public static String doGet(String url, Map params, String charset) { + if(charset==null||charset.trim().length()<1) charset="UTF-8"; + if (StringUtils.isBlank(url)) { + return null; + } + + try { + if (params != null && !params.isEmpty()) { + List pairs = new ArrayList(params.size()); + for (Map.Entry entry : params.entrySet()) { + String value = entry.getValue(); + if (value != null) { + pairs.add(new BasicNameValuePair(entry.getKey(), value)); + } + } + // 将请求参数和url进行拼接 + url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); + } + HttpGet httpGet = new HttpGet(url); + CloseableHttpResponse response = httpClient.execute(httpGet); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + httpGet.abort(); + throw new RuntimeException("HttpClient,error status code :" + statusCode); + } + HttpEntity entity = response.getEntity(); + String result = null; + if (entity != null) { + result = EntityUtils.toString(entity, charset); + } + EntityUtils.consume(entity); + response.close(); + if(!"UTF-8".equals(getEncoding(result))) result=GBKtoUTF8(result); + + return result; + } catch (Exception e) { + System.out.println("url错误:::"+e.toString()); + e.printStackTrace(); + } + return null; + } + + + /** + * HTTP Post 获取内容 + * @param url 请求的url地址 ?之前的地址 + * @param params 请求的参数 + * @param charset 编码格式 + * @return 页面内容 + * @throws IOException + */ + public static String doPost(String url, Map params, String charset) { + if(charset==null||charset.trim().length()<1) charset="UTF-8"; + if (StringUtils.isBlank(url)) { + return null; + } + + List pairs = null; + if (params != null && !params.isEmpty()) { + pairs = new ArrayList(params.size()); + for (Map.Entry entry : params.entrySet()) { + String value = entry.getValue(); + if (value != null) { + pairs.add(new BasicNameValuePair(entry.getKey(), value)); + } + } + } + HttpPost httpPost = new HttpPost(url); + CloseableHttpResponse response = null; + try { + if (pairs != null && pairs.size() > 0) { + httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET)); + } + + response = httpClient.execute(httpPost); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + httpPost.abort(); + throw new RuntimeException("HttpClient,error status code :" + statusCode); + } + HttpEntity entity = response.getEntity(); + String result = null; + if (entity != null) { + result = EntityUtils.toString(entity, charset); + } + EntityUtils.consume(entity); + if(!"UTF-8".equals(getEncoding(result))) result=GBKtoUTF8(result); + return result; + } catch (Exception e) { + return ""; + } finally { + if (response != null) + try { + response.close(); + } catch (IOException e) {} + } + } + + /** + * HTTPS Get 获取内容 + * @param url 请求的url地址 ?之前的地址 + * @param params 请求的参数 + * @param charset 编码格式 + * @return 页面内容 + */ + public static String doGetSSL(String url, Map params, String charset) { + if(charset==null||charset.trim().length()<1) charset="UTF-8"; + if (StringUtils.isBlank(url)) { + return null; + } + + try { + if (params != null && !params.isEmpty()) { + List pairs = new ArrayList(params.size()); + for (Map.Entry entry : params.entrySet()) { + String value = entry.getValue(); + if (value != null) { + pairs.add(new BasicNameValuePair(entry.getKey(), value)); + } + } + url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); + } + HttpGet httpGet = new HttpGet(url); + + // https 注意这里获取https内容,使用了忽略证书的方式,当然还有其他的方式来获取https内容 + CloseableHttpClient httpsClient = HttpUtils.createSSLClientDefault(); + CloseableHttpResponse response = httpsClient.execute(httpGet); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + httpGet.abort(); + throw new RuntimeException("HttpClient,error status code :" + statusCode); + } + HttpEntity entity = response.getEntity(); + String result = null; + if (entity != null) { + result = EntityUtils.toString(entity, charset); + } + EntityUtils.consume(entity); + response.close(); + if(!"UTF-8".equals(getEncoding(result))) result=GBKtoUTF8(result); + return result; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * 这里创建了忽略整数验证的CloseableHttpClient对象 + * @return + */ + public static CloseableHttpClient createSSLClientDefault() { + try { + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { + // 信任所有 + public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { + return true; + } + }).build(); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); + return HttpClients.custom().setSSLSocketFactory(sslsf).build(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (KeyStoreException e) { + e.printStackTrace(); + } + return HttpClients.createDefault(); + } + + /** + * 这里创建了忽略整数验证的CloseableHttpClient对象 + * @return + */ + public static CloseableHttpClient createSSLClientCookie(CookieStore cookie) { + try { + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { + // 信任所有 + public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { + return true; + } + }).build(); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); + return HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCookieStore(cookie).build(); + } catch (KeyManagementException e) { + e.printStackTrace(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } catch (KeyStoreException e) { + e.printStackTrace(); + } + return HttpClients.createDefault(); + } + + /** + * 发送post请求 + * @param url 请求地址 + * @param json json格式字符串 + * @param contentType 这里用 "application/json" + * @return + */ + public static String post(String url, String json, String contentType,String charset) { + if(charset==null||charset.trim().length()<1) charset="UTF-8"; + if("json".equals(contentType)) contentType="application/json"; + HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); + //HttpClient + CloseableHttpClient client = httpClientBuilder.build(); + client = (CloseableHttpClient) wrapClient(client); + HttpPost post = new HttpPost(url); + try { + StringEntity s = new StringEntity(json, "utf-8"); + if (StringUtils.isBlank(contentType)) { + s.setContentType("application/json"); + } + s.setContentType(contentType); + post.setEntity(s); + HttpResponse res = client.execute(post); + HttpEntity entity = res.getEntity(); + String str = EntityUtils.toString(entity, charset); + if(!"UTF-8".equals(getEncoding(str))) str=GBKtoUTF8(str); + return str; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + + private static org.apache.http.client.HttpClient wrapClient(HttpClient base) { + try { + SSLContext ctx = SSLContext.getInstance("TLSv1"); + X509TrustManager tm = new X509TrustManager() { + public void checkClientTrusted(X509Certificate[] xcs, + String string) throws CertificateException { + } + + public void checkServerTrusted(X509Certificate[] xcs, + String string) throws CertificateException { + } + + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + ctx.init(null, new TrustManager[]{tm}, null); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[]{"TLSv1"}, null, + SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); + CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); + return httpclient; + + } catch (Exception ex) { + return null; + } + } + + + //正则找出所有 + public static String getUrl(String s){ + String regex = "http[s]?:\\/\\/([\\w]+\\.)+[\\w]+([\\w./?%&=]*)?"; + Pattern pattern = Pattern.compile(regex); + Matcher m = pattern.matcher(s); + String r=""; + while(m.find()){ + r+=m.group()+","; + } + return r; + } + + /** + * 检查url是否可访问 + * @param url + * @return + */ + public static boolean ckUrl(String url) { + + if (StringUtils.isBlank(url)) { + return false; + } + HttpGet httpGet = new HttpGet(url); + try { + CloseableHttpResponse response = httpClient.execute(httpGet); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) return false; + } catch (Exception e) { + String s = e.getMessage(); + if("Timeout waiting for connection from pool".equals(s)) return true; + return false; + } + + return true; + } + + /**检查字符串编码格式*/ + public static String getEncoding(String str) + { + String encode; + + encode = "UTF-16"; + try + { + if(str.equals(new String(str.getBytes(), encode))) + { + return encode; + } + } + catch(Exception ex) {} + + encode = "ASCII"; + try + { + if(str.equals(new String(str.getBytes(), encode))) + { + //字符串 str 中仅由数字和英文字母组成,无法识别其编码格式 + return "UTF-8"; + } + } + catch(Exception ex) {} + + encode = "ISO-8859-1"; + try + { + if(str.equals(new String(str.getBytes(), encode))) + { + return encode; + } + } + catch(Exception ex) {} + + encode = "GB2312"; + try + { + if(str.equals(new String(str.getBytes(), encode))) + { + return encode; + } + } + catch(Exception ex) {} + + encode = "UTF-8"; + try + { + if(str.equals(new String(str.getBytes(), encode))) + { + return encode; + } + } + catch(Exception ex) {} + + /* + *......待完善 + */ + + return "UTF-8"; + } + + /**将字符串转换字符编码*/ + public static String GBKtoUTF8(String str) { + if("UTF-8".equals(getEncoding(str))) return str; + + return getUTF8StringFromGBKString(str); + + } + + public static String getUTF8StringFromGBKString(String gbkStr) { + try { + return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new InternalError(); + } + } + + public static byte[] getUTF8BytesFromGBKString(String gbkStr) { + int n = gbkStr.length(); + byte[] utfBytes = new byte[3 * n]; + int k = 0; + for (int i = 0; i < n; i++) { + int m = gbkStr.charAt(i); + if (m < 128 && m >= 0) { + utfBytes[k++] = (byte) m; + continue; + } + utfBytes[k++] = (byte) (0xe0 | (m >> 12)); + utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f)); + utfBytes[k++] = (byte) (0x80 | (m & 0x3f)); + } + if (k < utfBytes.length) { + byte[] tmp = new byte[k]; + System.arraycopy(utfBytes, 0, tmp, 0, k); + return tmp; + } + return utfBytes; + } + + + /** + * 带有cookie和header 的post请求 + * @param url + * @param params + * @param cookie + * @param header + * @return + */ + public static String doPost2(String url, Map params, CookieStore cookie,Map header,String charset) { + if(charset==null||charset.trim().length()<1) charset="UTF-8"; + if (StringUtils.isBlank(url)) { + return null; + } + + List pairs = null; + if (params != null && !params.isEmpty()) { + pairs = new ArrayList(params.size()); + for (Map.Entry entry : params.entrySet()) { + String value = entry.getValue(); + if (value != null) { + pairs.add(new BasicNameValuePair(entry.getKey(), value)); + } + } + } + HttpPost httpPost = new HttpPost(url); + + Set> set = header.entrySet(); + Iterator> s = set.iterator(); + while (s.hasNext()) { + Map.Entry m = (Map.Entry) s.next(); + httpPost.addHeader(m.getKey().toString(),m.getValue().toString()); + } + + CloseableHttpResponse response = null; + try { + if (pairs != null && pairs.size() > 0) { + httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET)); + } + + CloseableHttpClient httpClientc = HttpUtils.createSSLClientCookie(cookie); + response = httpClientc.execute(httpPost); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + httpPost.abort(); + throw new RuntimeException("HttpClient,error status code :" + statusCode); + } + HttpEntity entity = response.getEntity(); + String result = null; + if (entity != null) { + result = EntityUtils.toString(entity, charset); + } + EntityUtils.consume(entity); + if(!"UTF-8".equals(getEncoding(result))) result=GBKtoUTF8(result); + return result; + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (response != null) + try { + response.close(); + } catch (IOException e) {e.printStackTrace();} + } + return null; + } + + public static String doGet2(String url, Map params, CookieStore cookie,Map header,String charset) { + if(charset==null||charset.trim().length()<1) charset="UTF-8"; + if (StringUtils.isBlank(url)) { + return null; + } + + try { + if (params != null && !params.isEmpty()) { + List pairs = new ArrayList(params.size()); + for (Map.Entry entry : params.entrySet()) { + String value = entry.getValue(); + if (value != null) { + pairs.add(new BasicNameValuePair(entry.getKey(), value)); + } + } + url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); + } + HttpGet httpGet = new HttpGet(url); + + Set> set = header.entrySet(); + Iterator> s = set.iterator(); + while (s.hasNext()) { + Map.Entry m = (Map.Entry) s.next(); + httpGet.addHeader(m.getKey().toString(),m.getValue().toString()); + } + + // https 注意这里获取https内容,使用了忽略证书的方式,当然还有其他的方式来获取https内容 + CloseableHttpClient httpsClient = HttpUtils.createSSLClientCookie(cookie); + CloseableHttpResponse response = httpsClient.execute(httpGet); + int statusCode = response.getStatusLine().getStatusCode(); + if (statusCode != 200) { + httpGet.abort(); + throw new RuntimeException("HttpClient,error status code :" + statusCode); + } + HttpEntity entity = response.getEntity(); + String result = null; + if (entity != null) { + result = EntityUtils.toString(entity, charset); + } + EntityUtils.consume(entity); + response.close(); + if(!"UTF-8".equals(getEncoding(result))) result=GBKtoUTF8(result); + return result; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + + +} diff --git a/src/sc545/pay/utils/ImgUtils.java b/src/sc545/pay/utils/ImgUtils.java new file mode 100644 index 0000000..2ae62f0 --- /dev/null +++ b/src/sc545/pay/utils/ImgUtils.java @@ -0,0 +1,244 @@ +package sc545.pay.utils; + + +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.*; + +import javax.imageio.ImageIO; + +import net.coobird.thumbnailator.Thumbnails; +import net.coobird.thumbnailator.geometry.Positions; +import sun.misc.BASE64Encoder; + +import com.google.zxing.*; +import com.google.zxing.common.BitMatrix; + +public class ImgUtils { + + public static void main(String[] args) throws Exception { + + } + + + + + +private static final int BLACK = 0xFF000000; +private static final int WHITE = 0xFFFFFFFF; +private static BufferedImage toBufferedImage(BitMatrix matrix) { + int width = matrix.getWidth(); + int height = matrix.getHeight(); + BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); + } + } + return image; +} + +private static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { + BufferedImage image = toBufferedImage(matrix); + if (!ImageIO.write(image, format, file)) { + throw new IOException("Could not write an image of format " + format + " to " + file); + } +} + +/** + * 删除二维码白边 + * @param matrix + * @return + */ +public static BitMatrix deleteWhite(BitMatrix matrix) { + int[] rec = matrix.getEnclosingRectangle(); + int resWidth = rec[2] + 1; + int resHeight = rec[3] + 1; + + BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); + resMatrix.clear(); + for (int i = 0; i < resWidth; i++) { + for (int j = 0; j < resHeight; j++) { + if (matrix.get(i + rec[0], j + rec[1])) + resMatrix.set(i, j); + } + } + return resMatrix; +} + + +/** + * 生成一张二维码图片文件 + * @param content 二维码内容 + * @param widthHeight 宽高度 + * @param path 图片存储路径(不带文件名) + * @return + */ +public static String QrImgFile(String content,int widthHeight,String path) { + try { + String codeName = UUID.randomUUID().toString();// 二维码的图片名 + String imageType = "jpg";// 图片类型 + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + Map hints = new HashMap(); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints); + bitMatrix= deleteWhite(bitMatrix); + // BufferedImage imgbuf = toBufferedImage(bitMatrix); + File file1 = new File(path, codeName + "." + imageType); + writeToFile(bitMatrix, imageType, file1); + return path+codeName + "." + imageType; + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; +} + + +/** + * 生成一张二维码图片(BufferedImage) + * @param content 二维码内容 + * @param widthHeight 宽高度 + * @return + */ +public static BufferedImage QrImgBuf(String content,int widthHeight) { + try { + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + Map hints = new HashMap(); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints); + bitMatrix= deleteWhite(bitMatrix); + BufferedImage imgbuf = toBufferedImage(bitMatrix); + return imgbuf; + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; +} + + + +/** + * 生成一张二维码图片(base64)
+ * data:image/jpg;base64,base64_code + * @param content 二维码内容 + * @param widthHeight 宽高度 + * @return + */ +public static String QrImgB64(String content,int widthHeight) { + try { + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + Map hints = new HashMap(); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints); + bitMatrix= deleteWhite(bitMatrix); + BufferedImage imgbuf = toBufferedImage(bitMatrix); + ByteArrayOutputStream os = new ByteArrayOutputStream();//新建流。 + ImageIO.write(imgbuf, "jpg", os);//利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。 + byte b[] = os.toByteArray();//从流中获取数据数组。 + String str = new BASE64Encoder().encode(b); + return str; + + } catch (Exception e) { + e.printStackTrace(); + } + + return null; +} + + +/** + * 图片质量压缩 + * @param img 文件流 + * @param quality 压缩质量 0~1/1为最高质量 + * @return + */ +public static BufferedImage rarImgBuf(InputStream img, double quality) { + BufferedImage buf =null; + try { + buf = Thumbnails.of(img).scale(1f).outputQuality(quality).asBufferedImage(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return buf; +} + +/** + * 图片质量压缩 + * @param img 文件地址 + * @param quality 压缩质量 0~1/1为最高质量 + * @return + */ +public static File rarImgFile(File img, double quality) { + File arg0 = img; + try { + Thumbnails.of(img).scale(1f).outputQuality(quality).toFile(arg0); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return arg0; +} + +/** + * 裁剪图片
+ * 从左上角开始裁切
+ * 另存图片保持等比缩放,若填写的高度不符合自动调整为等比例 + * + * @param img 图片文件 + * @param p 裁切位置 Positions.TOP/BOTTOM_LEFT/RIGHT、CENTER + * @param x 裁切x轴范围 + * @param y 裁切y轴范围 + * @param width 另存图片的宽度 + * @param height 另存图片的高度 + * @return + */ +public static File cutImgFile(File img,Positions p,int x,int y,int width,int height) { + File arg0 = img; + try { + Thumbnails.of(img).sourceRegion(p, x, y).size(width, height).keepAspectRatio(true).toFile(arg0); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return arg0; +} + + +/** + * 裁剪图片
+ * 从左上角开始裁切
+ * 另存图片保持等比缩放,若填写的高度不符合自动调整为等比例 + * + * @param img 图片流 + * @param p 裁切位置 Positions.TOP/BOTTOM_LEFT/RIGHT、CENTER + * @param x 裁切x轴范围 + * @param y 裁切y轴范围 + * @param width 另存图片的宽度 + * @param height 另存图片的高度 + * @return + */ +public static BufferedImage cutImgBuf(InputStream img,Positions p,int x,int y,int width,int height) { + BufferedImage buf =null; + try { + buf=Thumbnails.of(img).sourceRegion(p, x, y).size(width, height).keepAspectRatio(true).asBufferedImage(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return buf; +} + + + +} diff --git a/src/sc545/pay/utils/MailUtils.java b/src/sc545/pay/utils/MailUtils.java new file mode 100644 index 0000000..be7a3f2 --- /dev/null +++ b/src/sc545/pay/utils/MailUtils.java @@ -0,0 +1,85 @@ +package sc545.pay.utils; + +import java.util.Properties; + +import javax.mail.Authenticator; +import javax.mail.Message; +import javax.mail.PasswordAuthentication; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +public class MailUtils { + + private static final String USER = "scboxs@163.com"; // 发件人称号,同邮箱地址 + private static final String HOST = "smtp.163.com"; // SMTP服务器地址 + private static final String PASSWORD = "FUTSRKZXNDRSFXUW"; // 如果是qq邮箱可以使户端授权码,或者登录密码 + + public static void main(String[] args) { + boolean t = sendMail("1782158860@qq.com", "这是一个测试邮件", "【顺诚百宝箱】测试邮件"); + System.out.println(t); + } + + + /** + * + * @param to 收件人邮箱 + * @param text 邮件正文 + * @param title 标题 + */ + /* 发送验证信息的邮件 */ + public static boolean sendMail(String to, String text, String title){ + try { + final Properties props = new Properties(); + props.put("mail.smtp.auth", "true"); + props.put("mail.smtp.host", HOST); + + // 发件人的账号 + props.put("mail.user", USER); + //发件人的密码 + props.put("mail.password", PASSWORD); + + // 构建授权信息,用于进行SMTP进行身份验证 + Authenticator authenticator = new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + // 用户名、密码 + String userName = props.getProperty("mail.user"); + String password = props.getProperty("mail.password"); + return new PasswordAuthentication(userName, password); + } + }; + // 使用环境属性和授权信息,创建邮件会话 + Session mailSession = Session.getInstance(props, authenticator); + // 创建邮件消息 + MimeMessage message = new MimeMessage(mailSession); + // 设置发件人 + String username = props.getProperty("mail.user"); + InternetAddress form = new InternetAddress(username); + message.setFrom(form); + message.setDescription("欢迎关注微信公众号【顺诚百宝箱】\n全网VIP视频、聚合全网小说,音乐等APP,破解软件游戏,大额优惠券福利,更多功能等你发现~"); + + // 设置收件人 + InternetAddress toAddress = new InternetAddress(to); + message.setRecipient(Message.RecipientType.TO, toAddress); + + // 设置邮件标题 + message.setSubject(title); + + // 设置邮件的内容体 + message.setContent(text, "text/html;charset=UTF-8"); + // 发送邮件 + Transport transport = mailSession.getTransport("smtp"); + //设置授权码 + transport.connect(username,"授权码"); + transport.sendMessage(message,message.getAllRecipients()); + transport.close(); + return true; + }catch (Exception e){ + e.printStackTrace(); + } + return false; + } + +} diff --git a/src/sc545/pay/utils/ReadTxt.java b/src/sc545/pay/utils/ReadTxt.java new file mode 100644 index 0000000..973089a --- /dev/null +++ b/src/sc545/pay/utils/ReadTxt.java @@ -0,0 +1,716 @@ +package sc545.pay.utils; + +import java.io.*; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map.Entry; +import java.util.Random; + +import javax.servlet.ServletContext; + +public class ReadTxt { + + public static void main(String[] args) { + + + //上月新增访客 + Calendar cal = Calendar.getInstance(); + int month = cal.get(Calendar.MONTH); + int year = cal.get(Calendar.YEAR); + if(month==0){ + month=12; + year=year-1; + } + String ms = String.format("%02d", month); + String ys = String.format("%04d", year); + + String smm=ys+"-"+ms; + String smck= ReadTxt.getSetting(null, "count.ini",smm, "0"); + + String a = ReadTxt.getSetting(null, "setting.ini", "pageNullTelTxt","提交需求"); + System.out.println(a+smm+"\n"+ms+"\n"+ys); + + } + + /** + * 按行读取txt文件 + * + * @param path + * 文件地址(默认D:\\开头) + * @return ArrayList 返回每行数据为一个items的集合 + */ + public static ArrayList readFileLine(ServletContext servletContext, String path) { + + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + if (servletContext == null) { + if(path.indexOf(":") <= 0&&path.indexOf("/") <0) + path = "D:\\" + path; + } else { + path = servletContext.getRealPath(path); + } + + + + ArrayList strarr = null; + try { + File file = new File(path); + if (file.isFile() && file.exists()) { // 判断文件是否存在 + InputStreamReader read = new InputStreamReader( + new FileInputStream(file), "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(read); + String lineTxt = null; + strarr = new ArrayList(); + while ((lineTxt = bufferedReader.readLine()) != null) { + + strarr.add(lineTxt); + } + + read.close(); + } else { + strarr = null; + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return strarr; + } + + + /** + * 按行读取文件 + * debug模式 + * @param path + * 文件地址(默认D:\\开头) + * @return ArrayList 返回每行数据为一个items的集合 + */ + public static ArrayList readFileLineDEBUG(String path) { + + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + //debug模式下把所有路径改为tomcat下的真实路径 + if(path.indexOf("/")==0){ + String tomcat_path = "D:/java/Tomcat_8.5.23/webapps/ROOT"; + path =tomcat_path+path; + } + + ArrayList strarr = null; + try { + File file = new File(path); + if (file.isFile() && file.exists()) { // 判断文件是否存在 + InputStreamReader read = new InputStreamReader( + new FileInputStream(file), "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(read); + String lineTxt = null; + strarr = new ArrayList(); + while ((lineTxt = bufferedReader.readLine()) != null) { + + strarr.add(lineTxt); + } + + read.close(); + } else { + strarr = null; + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return strarr; + } + + + /** + * 写入txt文档,已存在就修改,否则写入末尾,自动加换行 (文件格式:key=value,换行分隔) + * + * @param path + * 文件地址(默认D:\\开头) + * @param keyname + * 要修改的参数名 + * @param content + * 要修改的参数值 + */ + public static void writeSetting(ServletContext servletContext, String path, String keyname, String content) { + + /**************/ + // 如果存在,则追加内容;如果文件不存在,则创建文件 + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + if (servletContext == null) { + if(path.indexOf(":") <= 0&&path.indexOf("/") <0) + path = "D:\\" + path; + } else { + path = servletContext.getRealPath(path); + } + + try { + File file = new File(path); + if (file.isFile() && file.exists()) { // 判断文件是否存在 + InputStreamReader read = new InputStreamReader( + new FileInputStream(file), "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(read); + String lineTxt = null; + boolean isread = false;// 是否读取到该行并修改 + // 将内容全部读出来,存为新的数据流 + // 读到要修改的行进行修改存入,否则原样读取存入 + StringBuffer buf = new StringBuffer(); + while ((lineTxt = bufferedReader.readLine()) != null) { + if (lineTxt.startsWith(keyname + "=")) { + buf.append(keyname + "=" + content + "\r\n"); + isread = true; + } else { + buf.append(lineTxt + "\r\n"); + } + } + read.close(); + if (!isread) {// 没有读取到,写入末尾 + buf.append(keyname + "=" + content + "\r\n"); + } + + // 把新内容覆盖写入文件 + PrintWriter out = new PrintWriter(new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(path), + "UTF-8"))); + out.write(buf.toString()); + out.flush(); + out.close(); + + } else {// 不存在,创建写入 + String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/")); + File file1 = new File(path2); + // 如果文件夹不存在则创建 + if (!file1.exists() && !file1.isDirectory()) { + file1.mkdirs(); + } + File file2 = new File(path); + if (!file2.exists()) { + file2.createNewFile(); + } + + PrintWriter out = new PrintWriter(new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(path), + "UTF-8"))); + out.write(keyname + "=" + content + "\r\n"); + out.flush(); + out.close(); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + /**************/ + + } + + /** + * 读取txt配置,返回map集合(文件格式:key=value,换行分隔) + * + * @param path + * 文件地址(默认D:\\开头) + * @return hashmap + */ + public static HashMap readSetting(ServletContext servletContext, String path) { + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + if (servletContext == null) { + if(path.indexOf(":") <= 0&&path.indexOf("/") <0) + path = "D:\\" + path; + } else { + path = servletContext.getRealPath(path); + } + + HashMap strarr = null; + try { + File file = new File(path); + if (file.isFile() && file.exists()) { // 判断文件是否存在 + InputStreamReader read = new InputStreamReader( + new FileInputStream(file), "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(read); + String lineTxt = null; + strarr = new HashMap(); + while ((lineTxt = bufferedReader.readLine()) != null) { + if(lineTxt.indexOf("#")==0){ + continue; + } + String[] arr = new String[2]; + if (lineTxt.split("=").length >= 2) { + arr[0] = lineTxt.split("=")[0]; + arr[1] = lineTxt.replace(arr[0]+"=", ""); + strarr.put(arr[0], arr[1]); + } + } + + read.close(); + } else { + strarr = null; + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return strarr; + } + + + /** + * 获取配置文件中所有设置属性(含注释)
+ * map.get("z") 取注释
+ * map.get("k") 取key
+ * map.get("v") 取value
+ * + * + * @param path + * 文件地址(默认D:\\开头) + * + * @param t 只取以此字符开头的,不限制填null + * @param st 从以此字符开头的行开始读取,不限制填null + * @param et 读到以此字符开头的行结束,不限制填null + * @return + */ + public static ArrayList> getSettingAll(ServletContext servletContext, String path,String t,String st,String et) { + if(st==null||st.length()<1) st=""; + if(et==null||et.length()<1) et=""; + if(t==null||t.length()<1) t=""; + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + if (servletContext == null) { + if(path.indexOf(":") <= 0&&path.indexOf("/") <0) + path = "D:\\" + path; + } else { + path = servletContext.getRealPath(path); + } + + ArrayList> list=new ArrayList<>(); + try { + File file = new File(path); + if (file.isFile() && file.exists()) { // 判断文件是否存在 + InputStreamReader read = new InputStreamReader( + new FileInputStream(file), "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(read); + String lineTxt = null; + String zs="";//注释文本 + while ((lineTxt = bufferedReader.readLine()) != null) { + if((!"".equals(st))||lineTxt.indexOf(st)!=0) continue; + if((!"".equals(et))&&lineTxt.indexOf(et)==0) break; + HashMap map = new HashMap(); + if(lineTxt.indexOf("#")==0){ + zs=lineTxt; + continue; + } + String[] arr = new String[2]; + if (lineTxt.split("=").length >= 2&&lineTxt.indexOf(t)==0) { + arr[0] = lineTxt.split("=")[0]; + arr[1] = lineTxt.replace(arr[0]+"=", ""); + map.put("z", zs); + map.put("k", arr[0]); + map.put("v", arr[1]); + list.add(map); + //把注释也加进去 + zs=""; + } + } + + read.close(); + } else { + list = null; + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return list; + } + + /** + * 读取txt配置文件的某一项设置值 (文件格式:key=value,换行分隔) + * + * @param path + * 文件地址 + * @param settingName + * 设置名 + * @param nullString + * 设置值为空时默认返回的内容 + * @return string + */ + public static String getSetting(ServletContext servletContext, String path, String settingName,String nullString) { + HashMap setting = ReadTxt.readSetting(servletContext,path); + String val = setting == null ? nullString : setting.get(settingName); + val = val == null ? "" : val; + return "".equals(val.trim()) ? nullString : val; + } + + /** + * 获取所有设置名以[settingName]开头的数据 + * */ + public static ArrayList getSettingW(ServletContext servletContext, String path, String settingName) { + HashMap setting = ReadTxt.readSetting(servletContext,path); + if(setting==null||setting.size()<1) return null; + Iterator> it = setting.entrySet().iterator(); + ArrayList rs=new ArrayList<>(); + while (it.hasNext()) { + Entry en=it.next(); + String k = en.getKey(); + String v = en.getValue(); + if(k.indexOf(settingName)==0){ + rs.add(k+"="+v); + } + } + + return rs; + } + + /** + * 删除某一项设置值 (文件格式:key=value,换行分隔) + * + * @param path + * 文件地址 + * @param settingName + * 设置名 + * @param nullString + * 设置值为空时默认返回的内容 + * @return string + */ + public static void delSetting(ServletContext servletContext, String path, String settingName) { + + + /**************/ + // 如果存在,则追加内容;如果文件不存在,则创建文件 + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + if (servletContext == null) { + if(path.indexOf(":") <= 0&&path.indexOf("/") <0) + path = "D:\\" + path; + } else { + path = servletContext.getRealPath(path); + } + + try { + File file = new File(path); + if (file.isFile() && file.exists()) { // 判断文件是否存在 + InputStreamReader read = new InputStreamReader( + new FileInputStream(file), "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(read); + String lineTxt = null; + // 将内容全部读出来,存为新的数据流 + // 读到要修改的行进行修改存入,否则原样读取存入 + StringBuffer buf = new StringBuffer(); + while ((lineTxt = bufferedReader.readLine()) != null) { + if (lineTxt.startsWith(settingName + "=")) { + } else { + buf.append(lineTxt + "\r\n"); + } + } + read.close(); + + // 把新内容覆盖写入文件 + PrintWriter out = new PrintWriter(new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(path), + "UTF-8"))); + out.write(buf.toString()); + out.flush(); + out.close(); + + } else {// 不存在,创建 + String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/")); + File file1 = new File(path2); + // 如果文件夹不存在则创建 + if (!file1.exists() && !file1.isDirectory()) { + file1.mkdirs(); + } + File file2 = new File(path); + if (!file2.exists()) { + file2.createNewFile(); + } + + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + /**************/ + + } + + + /** + * 删除设置名以[settingName]开头的数据 + * @param servletContext + * @param path + * @param settingName + */ + public static void delSettingW(ServletContext servletContext, String path, String settingName) { + + + /**************/ + // 如果存在,则追加内容;如果文件不存在,则创建文件 + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + if (servletContext == null) { + if(path.indexOf(":") <= 0&&path.indexOf("/") <0) + path = "D:\\" + path; + } else { + path = servletContext.getRealPath(path); + } + + try { + File file = new File(path); + if (file.isFile() && file.exists()) { // 判断文件是否存在 + InputStreamReader read = new InputStreamReader( + new FileInputStream(file), "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(read); + String lineTxt = null; + // 将内容全部读出来,存为新的数据流 + // 读到要修改的行进行修改存入,否则原样读取存入 + StringBuffer buf = new StringBuffer(); + while ((lineTxt = bufferedReader.readLine()) != null) { + if (lineTxt.split("=")[0].indexOf(settingName)==0) { + } else { + buf.append(lineTxt + "\r\n"); + } + } + read.close(); + + // 把新内容覆盖写入文件 + PrintWriter out = new PrintWriter(new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(path), + "UTF-8"))); + out.write(buf.toString()); + out.flush(); + out.close(); + + } else {// 不存在,创建 + String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/")); + File file1 = new File(path2); + // 如果文件夹不存在则创建 + if (!file1.exists() && !file1.isDirectory()) { + file1.mkdirs(); + } + File file2 = new File(path); + if (!file2.exists()) { + file2.createNewFile(); + } + + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + /**************/ + + } + + + /** + * 删除过期的所有设置值 (文件格式:key=value,换行分隔) + *
key为检测源 + * @param servletContext + * @param path 路径 + * @param d 有效天数 + */ + public static void delOutDateSetting(ServletContext servletContext, String path, int d) { + + + /**************/ + // 如果存在,则追加内容;如果文件不存在,则创建文件 + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + if (servletContext == null) { + if(path.indexOf(":") <= 0&&path.indexOf("/") <0) + path = "D:\\" + path; + } else { + path = servletContext.getRealPath(path); + } + + try { + File file = new File(path); + if (file.isFile() && file.exists()) { // 判断文件是否存在 + InputStreamReader read = new InputStreamReader( + new FileInputStream(file), "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(read); + String lineTxt = null; + // 将内容全部读出来,存为新的数据流 + // 读到要修改的行进行修改存入,否则原样读取存入 + StringBuffer buf = new StringBuffer(); + boolean ts=false; + while ((lineTxt = bufferedReader.readLine()) != null) { + + if(lineTxt.indexOf("=")>0&&lineTxt.indexOf("#")<0){ + String[] ls = lineTxt.split("="); + int has = ls[0].length()-ls[0].replaceAll("-", "").length(); + if(has>1){//日期时间 + if(Utils.dateout(ls[0], d)){ + buf.append(lineTxt + "\r\n"); + }else{ + ts=true; + }//过期 + }else{//月份时间 + buf.append(lineTxt + "\r\n"); + } + + }else{//注释或者不是setting + buf.append(lineTxt + "\r\n"); + } + + } + read.close(); + if(ts){ + // 把新内容覆盖写入文件 + PrintWriter out = new PrintWriter(new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(path), + "UTF-8"))); + out.write(buf.toString()); + out.flush(); + out.close(); + } + + } else {// 不存在,创建 + String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/")); + File file1 = new File(path2); + // 如果文件夹不存在则创建 + if (!file1.exists() && !file1.isDirectory()) { + file1.mkdirs(); + } + File file2 = new File(path); + if (!file2.exists()) { + file2.createNewFile(); + } + + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + /**************/ + + } + + + + /** + * 删除过期的所有设置值 (文件格式:key=value,换行分隔) + *
value为检测源 + * @param servletContext + * @param path 路径 + * @param d 有效天数 + */ + public static void delOutDateSettingValue(ServletContext servletContext, String path, int d) { + + + /**************/ + // 如果存在,则追加内容;如果文件不存在,则创建文件 + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + if (servletContext == null) { + if(path.indexOf(":") <= 0&&path.indexOf("/") <0) + path = "D:\\" + path; + } else { + path = servletContext.getRealPath(path); + } + + try { + File file = new File(path); + if (file.isFile() && file.exists()) { // 判断文件是否存在 + InputStreamReader read = new InputStreamReader( + new FileInputStream(file), "UTF-8"); + BufferedReader bufferedReader = new BufferedReader(read); + String lineTxt = null; + // 将内容全部读出来,存为新的数据流 + // 读到要修改的行进行修改存入,否则原样读取存入 + StringBuffer buf = new StringBuffer(); + boolean ts=false; + while ((lineTxt = bufferedReader.readLine()) != null) { + + if(lineTxt.indexOf("=")>0&&lineTxt.indexOf("#")<0){ + String[] ls = lineTxt.split("="); + int has = ls[1].length()-ls[1].replaceAll("-", "").length(); + if(has>1){//日期时间 + if(Utils.dateout(ls[1], d)){ + buf.append(lineTxt + "\r\n"); + }else{ + ts=true; + }//过期 + }else{//月份时间 + buf.append(lineTxt + "\r\n"); + } + + }else{//注释或者不是setting + buf.append(lineTxt + "\r\n"); + } + + } + read.close(); + if(ts){ + // 把新内容覆盖写入文件 + PrintWriter out = new PrintWriter(new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(path), + "UTF-8"))); + out.write(buf.toString()); + out.flush(); + out.close(); + } + + } else {// 不存在,创建 + String path2 = path.substring(0, path.replace("\\", "/").lastIndexOf("/")); + File file1 = new File(path2); + // 如果文件夹不存在则创建 + if (!file1.exists() && !file1.isDirectory()) { + file1.mkdirs(); + } + File file2 = new File(path); + if (!file2.exists()) { + file2.createNewFile(); + } + + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + /**************/ + + } + + + /** + * 将InputStream装换成某种字符编码的String + * + * @param in + * @param encoding + * @return + */ + public static String InputStreamTOString(InputStream in, String encoding) { + int BUFFER_SIZE = 4096; + String res = null; + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + byte[] data = new byte[BUFFER_SIZE]; + int count = -1; + try { + while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) { + outputStream.write(data, 0, count); + } + } catch (Exception e) { + e.printStackTrace(); + } + try { + res = new String(outputStream.toByteArray(), encoding); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return res; + } + + +} diff --git a/src/sc545/pay/utils/Utils.java b/src/sc545/pay/utils/Utils.java new file mode 100644 index 0000000..6fd0d3e --- /dev/null +++ b/src/sc545/pay/utils/Utils.java @@ -0,0 +1,1194 @@ +package sc545.pay.utils; + +import java.io.*; +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.time.DateUtils; + +public class Utils { + + public static void main(String[] args) { + String s = floatToString(0.01235788889f, 3,false); + System.out.println(s); + } + + /** + * 生成范围内的随机数 + * + * @param min + * 最小值(包含) + * @param max + * 最大值(不包含) + * @return + */ + public static int randomNum(int min, int max) { + int num = new Random().nextInt(max - min) + min; + return num; + } + + /** + * 生成范围内的随机小数 + * + * @param min + * 最小值(包含) + * @param max + * 最大值(不包含) + * @param w + * 小数点后保留位数 + * @return + */ + public static Double randomNumForDouble(int min, int max, int w) { + + BigDecimal db = new BigDecimal(Math.random() * (max - min) + min); + Double num = db.setScale(w, BigDecimal.ROUND_HALF_UP).doubleValue(); + return num; + } + + /** + * 时间转字符串,格式:yyyy-MM-dd + * + * @param d null为当前时间 + * + * @return + */ + public static String date2String(Date d) { + if(d==null) d=new Date(); + Date date = d; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String s = sdf.format(date); + return s; + } + + /** + * 时间转字符串 + * + * + * @param d null为当前时间 + * + * @param fm null为"yyyy-MM-dd HH:mm:ss" + * + * @return + */ + public static String date2String(Date d, String fm) { + if(d==null) d=new Date(); + Date date = d; + if (fm == null) + fm = "yyyy-MM-dd HH:mm:ss"; + SimpleDateFormat sdf = new SimpleDateFormat(fm); + String s = sdf.format(date); + return s; + } + + /** + * 字符串转时间,格式 yyyy-MM-dd + * + * @param s + * 时间字符串 + * @return + */ + public static Date string2Date(String s) { + try { + String string = s; + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date date = sdf.parse(string); + return date; + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; + } + + /** + * 字符串转时间
+ * fm为null时默认"yyyy-MM-dd HH:mm:ss" + * + * @param s + * 时间字符串 + * @param fm + * 格式 + * @return + */ + public static Date string2Date(String s, String fm) { + try { + String string = s; + if (fm == null) + fm = "yyyy-MM-dd HH:mm:ss"; + SimpleDateFormat sdf = new SimpleDateFormat(fm); + Date date = sdf.parse(string); + return date; + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; + } + + /** + * 时间加减法 + * + * @param d + * 时间 + * @param day + * 要操作的天数,正为加,负为减 + * @return + */ + public static Date dateadd(Date d, int day) { + if(d==null) d=new Date(); + Calendar yourd = Calendar.getInstance(); + yourd.setTime(d); + yourd.add(Calendar.DAY_OF_YEAR, day);// 日期加 + return yourd.getTime(); + } + + + /** + * 设置定时器启动时间 + * @param format 格式 yyyy-MM-dd 07:30:00 + * @param d 星期,1-7,其他数字默认当天 + * @return + */ + public static Date setTime(String format,int d) { + long daySpan=24 * 60 * 60 * 1000; + SimpleDateFormat sdf = new SimpleDateFormat(format); + Date startTime = new Date(); + try { + startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdf.format(new Date())); + } catch (ParseException e) { + e.printStackTrace(); + } + + int dd = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);//今天是星期几 + --dd; + if(dd==0) dd=7; + if(d>7) d=dd; + if(d<0){ + if (System.currentTimeMillis() > startTime.getTime()){ + startTime = new Date(startTime.getTime() + (daySpan)); + } + }else if(d==dd){ + if (System.currentTimeMillis() > startTime.getTime()){ + startTime = new Date(startTime.getTime() + (daySpan*7)); + } + }else{ + if(d>dd){ + startTime = new Date(startTime.getTime() + (daySpan*(d-dd-1))); + }else{ + startTime = new Date(startTime.getTime() + (daySpan*(7-dd+d-1))); + } + } + + return startTime; + } + + + /** + * 判断字符串是否为URL + * + * @param urls + * 需要判断的String类型url + * @return true:是URL;false:不是URL + */ + public static boolean isHttpUrl(String urls) { + boolean isurl = false; + String regex = "(((https|http)?://)?([a-z0-9]+[.])|(www.))" + + "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)";// 设置正则表达式 + + Pattern pat = Pattern.compile(regex.trim());// 对比 + Matcher mat = pat.matcher(urls.trim()); + isurl = mat.matches();// 判断是否匹配 + if (isurl) { + isurl = true; + } + return isurl; + } + + /** + * 缩短网址 + * + * @param longUrl + * @return shortUrl + */ + public static String shortUrl(String longUrl) { + // 以自己服务器做映射的修改 + String s2 = "http://api.t.sina.com.cn/short_url/shorten.json?source=3271760578&url_long=" + + longUrl; + s2 = "http://sa.sogou.com/gettiny?url=" + longUrl; + return s2; + } + + /** + * 判断某个时间是否过期。传进来一个旧时间,和有效天数,判断今天这个旧时间是否过期 + * + * @param d + * 旧时间 "2019-8-5" + * @param day + * 有效天数 + * @return true:没有过期;false:过期了 + */ + public static boolean dateout(String d, int day) { + if (d == null || "".equals(d) || "null".equals(d)) + return false; + Date date = Utils.dateadd(Utils.string2Date(d), day); + Date newdate = new Date(); + int i = date.compareTo(newdate); + if (i >= 0) { + return true; + } else { + return false; + } + } + + /** + * URL解析与转义 + * + * @param url + * url + * @param flg + * 1:转义,-1:解析 + * @return + */ + public static String doURL(String url, int flg) { + if (url == null || "".equals(url) || "null".equals(url)) + return ""; + String str = ""; + if (flg == 1) { + try { + str = java.net.URLEncoder.encode(url, "UTF-8");// 转义 + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } else if (flg == -1) { + try { + str = java.net.URLDecoder.decode(url, "UTF-8"); // 解析 + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + return str; + } + + /** + * 获取cookie的value + * + * @param cookies + * 数组 + * @param name + * @return value + */ + public static String getcookie(Cookie[] cookies, String name) { + String valueString = ""; + if (cookies != null) { + for (int i = 0; i < cookies.length; i++) { + if (name.equals(cookies[i].getName())) { + valueString = cookies[i].getValue(); + break; + } + } + } + return valueString; + } + + /** + * * selvet PrintWriter 输出一个html提示页,并且5秒后跳转到url + * + * @param out + * @param context + * 弹框内容 + * @param url + */ + public static void outHtml(PrintWriter out, String context, String url) { + // ///////////////////////输出HTML/////////////////////////////// + out.println(""); + out.println(""); + out.println(""); + out.println(" "); + out.println(" "); + out.println(" "); + out.println(" 提示信息"); + out.println(" "); + out.println(""); + out.println(""); + out.println("
"); + out.println("
"); + out.println("

"); + out.println(" "); + out.println("

"); + out.println("
"); + out.println("

" + context + "

"); + out.println("

5秒后自动跳转

"); + out.println(" 立即前往"); + out.println("
"); + out.println(" "); + out.println(""); + out.println(""); + out.flush(); + out.close(); + // ////////////////////////////////////////////////// + } + + /** + * * springmvc return 输出一个html提示页,并且5秒后跳转到url + * + * @param context + * 弹框内容 + * @param url + */ + public static String putHtml(String context, String url) { + // ///////////////////////输出HTML/////////////////////////////// + String s = ""; + s += ""; + s += ""; + s += ""; + s += " "; + s += " "; + s += " "; + s += " 提示信息"; + s += " "; + s += ""; + s += ""; + s += "
"; + s += "
"; + s += "

"; + s += " "; + s += "

"; + s += "
"; + s += "

" + context + "

"; + s += "

5秒后自动跳转

"; + s += " 立即前往"; + s += "
"; + s += " "; + s += ""; + return s += ""; + // ////////////////////////////////////////////////// + } + + /** + * 返回刷新 + * @return + */ + public static String goback(){ + String s = ""; + return s; + } + + /** + * 读取config.properties的值 + * + * @return + */ + public static String getValue(String name) { + String path = Utils.class.getResource("/").getPath(); + String value = null; + Properties prop = new Properties(); + try { + // 读取属性文件a.properties + FileInputStream in = new FileInputStream(path + + "/config.properties"); + prop.load(in); // /加载属性列表 + value = prop.getProperty(name); + in.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + return value; + } + + /** + * 利用DBUtils查询的listmap集给request设置setAttribute(map.key,map.value) + * + * @param request + * @param arr + * db查询的结果集(只能有一条记录 arr.get(0) ) + * @return + */ + public static HttpServletRequest setAttr(HttpServletRequest request, + List> arr) { + HttpServletRequest r = request; + Map m = arr.get(0); + for (Map.Entry entry : m.entrySet()) { + String v = String.valueOf(entry.getValue()); + if (v == null || "null".equals(v)) + v = ""; + r.setAttribute(entry.getKey(), v); + } + + return r; + } + + /** + * 如果是null、"null"、""、"undefined"、空格,都会返回"",否则返回原字符串 + * + * @param str + * @return + */ + public static String checkNull(String str) { + String str1 = str.trim(); + if (str1 == null || "".equals(str1) || "null".equals(str1) + || "undefined".equals(str1)) + return ""; + else + return str; + } + + /** + * 获取字符串中的数字(分正负)
+ * 严格模式(查取完数字和符号,第二个开始到最后必须是数字) + * + * @param str + * @return + */ + public static Long getNum2(String str) { + + str = str.trim(); + String str2 = ""; + if (str != null && !"".equals(str)) { + for (int i = 0; i < str.length(); i++) { + if ((str.charAt(i) >= 48 && str.charAt(i) <= 57) + || str.charAt(i) == 43 || str.charAt(i) == 45) { + str2 += str.charAt(i); + } + } + } + boolean isok = true; + for (int i = 1; i < str2.length(); i++) { + if (str2.charAt(i) == 43 || str2.charAt(i) == 45) { + isok = false; + } + } + if (!isok) + return getNum(str); + if ("".equals(str2)) + str2 = "0"; + return Long.valueOf(str2); + } + + /** + * 获取字符串中的时间
+ * yyy-MM-dd + * + * @param str + * @return + */ + public static Long getDateString(String str) { + + str = str.trim(); + String str2 = ""; + if (str != null && !"".equals(str)) { + for (int i = 0; i < str.length(); i++) { + if ((str.charAt(i) >= 48 && str.charAt(i) <= 57) + || str.charAt(i) == 43 || str.charAt(i) == 45) { + str2 += str.charAt(i); + } + } + } + boolean isok = true; + for (int i = 1; i < str2.length(); i++) { + if (str2.charAt(i) == 43 || str2.charAt(i) == 45) { + isok = false; + } + } + if (!isok) + return getNum(str); + if ("".equals(str2)) + str2 = "0"; + return Long.valueOf(str2); + } + + /** + * 获取字符串中的数字(分正负)
+ * 严格模式(查取完数字和符号,第二个开始到最后必须是数字) + * + * @param str + * @return + */ + public static double getNumDouble(String str) { + + str = str.trim(); + String str2 = ""; + if (str != null && !"".equals(str)) { + for (int i = 0; i < str.length(); i++) { + if ((str.charAt(i) >= 48 && str.charAt(i) <= 57) + || str.charAt(i) == 43 || str.charAt(i) == 45 + || str.charAt(i) == 46) { + str2 += str.charAt(i); + } + } + } + boolean isok = true; + for (int i = 1; i < str2.length(); i++) { + if (str2.charAt(i) == 43 || str2.charAt(i) == 45) { + isok = false; + } + } + if (!isok) + return Double.valueOf(getNum(str)); + if ("".equals(str2)) + str2 = "0"; + return Double.valueOf(str2); + } + + /** + * 获取字符串中的数字 + * + * @param str + * @return + */ + public static Long getNum(String str) { + + str = str.trim(); + String str2 = ""; + if (str != null && !"".equals(str)) { + for (int i = 0; i < str.length(); i++) { + if (str.charAt(i) >= 48 && str.charAt(i) <= 57) { + str2 += str.charAt(i); + } + } + } + if ("".equals(str2)) + str2 = "-1"; + return Long.valueOf(str2); + } + + /** + * 计算两个时间相差的秒数 + * + * @param endDate + * 结束时间 + * @param nowDate + * 开始时间 + * @return + */ + public static long getDatePoor(Date endDate, Date nowDate) { + + long nd = 1000 * 24 * 60 * 60;// 一天 + + long nh = 1000 * 60 * 60;// 一小时 + + long nm = 1000 * 60;// 一分钟 + + long ns = 1000;// 一秒 + + // 获得两个时间的毫秒时间差异 + + long diff = endDate.getTime() - nowDate.getTime(); + + long sec = diff / ns;// 计算差多少秒 + return sec; + + } + + /** + * 获取用户真实ip + * + * @param request + * @return + */ + public static String getIpAddr(HttpServletRequest request) { + String ip = request.getHeader("x-forwarded-for"); + if ((ip == null) || (ip.length() == 0) + || ("unknown".equalsIgnoreCase(ip))) { + ip = request.getHeader("Proxy-Client-IP"); + } + if ((ip == null) || (ip.length() == 0) + || ("unknown".equalsIgnoreCase(ip))) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if ((ip == null) || (ip.length() == 0) + || ("unknown".equalsIgnoreCase(ip))) { + ip = request.getRemoteAddr(); + } + return ip; + } + + /** + * 从字符串中截取出正确的时间 + * + * @param stringTime + * @return + */ + public static Date cutDate(String stringTime) { + String regs[] = { "\\d{4}年\\d{2}月\\d{2}日\\s\\d{2}时\\d{2}分\\d{2}秒", + "\\d{4}年\\d{2}月\\d{2}日\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{2}时\\d{2}分\\d{2}秒", + "\\d{4}年\\d{2}月\\d{2}日\\d{2}时\\d{2}分\\d{2}秒", + "\\d{4}年\\d{2}月\\d{2}日\\s\\d{2}时\\d{2}分", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{2}时\\d{2}分", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{1}时\\d{2}分", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{2}时\\d{2}分", + "\\d{4}年\\d{2}月\\d{2}日\\d{2}时\\d{2}分", + "\\d{4}年\\d{2}月\\d{2}日\\s\\d{2}时", + "\\d{4}年\\d{2}月\\d{2}日\\s\\d{1}时", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{2}时", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{1}时", + "\\d{4}年\\d{2}月\\d{2}日\\d{2}时", "\\d{4}年\\d{2}月\\d{2}日", + "\\d{4}年\\d{2}月\\d{1}日", "\\d{4}年\\d{1}月\\d{2}日", + "\\d{4}年\\d{1}月\\d{1}日", + "\\d{4}年\\d{2}月\\d{2}日\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{4}年\\d{2}月\\d{2}日\\s\\d{2}:\\d{1}:\\d{2}", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{2}:\\d{1}:\\d{2}", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{4}年\\d{2}月\\d{2}日\\d{2}:\\d{2}:\\d{2}", + "\\d{4}年\\d{2}月\\d{2}日\\s\\d{2}:\\d{2}", + "\\d{4}年\\d{2}月\\d{2}日\\s\\d{1}:\\d{2}", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{2}:\\d{2}", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{1}:\\d{2}", + "\\d{4}年\\d{2}月\\d{2}日\\d{2}:\\d{2}", + "\\d{4}年\\d{2}月\\d{2}日\\s\\d{2}", + "\\d{4}年\\d{2}月\\d{2}日\\s\\d{1}", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{2}", + "\\d{4}年\\d{1}月\\d{2}日\\s\\d{1}", + "\\d{4}年\\d{2}月\\d{2}日\\d{2}", + "\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{4}-\\d{2}-\\d{2}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{4}-\\d{1}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{4}-\\d{1}-\\d{2}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}", + "\\d{4}-\\d{2}-\\d{2}\\s\\d{1}:\\d{2}", + "\\d{4}-\\d{2}-\\d{2}\\s\\d{2}", "\\d{4}-\\d{2}-\\d{2}", + "\\d{4}-\\d{2}-\\d{1}", "\\d{4}-\\d{1}-\\d{2}", + "\\d{4}-\\d{1}-\\d{1}", + "\\d{4}-\\d{2}-\\d{2}\\s\\d{2}时\\d{2}分\\d{2}秒", + "\\d{4}-\\d{2}-\\d{2}\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{4}-\\d{1}-\\d{2}\\s\\d{2}时\\d{2}分\\d{2}秒", + "\\d{4}-\\d{1}-\\d{2}\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{4}-\\d{1}-\\d{1}\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{4}-\\d{2}-\\d{2}\\s\\d{2}时\\d{2}分", + "\\d{4}-\\d{2}-\\d{2}\\s\\d{1}时\\d{2}分", + "\\d{4}-\\d{1}-\\d{2}\\s\\d{2}时\\d{2}分", + "\\d{4}-\\d{1}-\\d{2}\\s\\d{1}时\\d{2}分", + "\\d{4}-\\d{2}-\\d{2}\\s\\d{2}时", + "\\d{4}-\\d{2}-\\d{2}\\s\\d{1}时", + "\\d{4}-\\d{1}-\\d{2}\\s\\d{2}时", + "\\d{4}-\\d{1}-\\d{2}\\s\\d{1}时", "\\d{4}.\\d{2}.\\d{2}", + "\\d{4}.\\d{2}.\\d{1}", "\\d{4}.\\d{1}.\\d{2}", + "\\d{4}.\\d{1}.\\d{1}", + "\\d{4}.\\d{2}.\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{4}.\\d{2}.\\d{2}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{4}.\\d{1}.\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{4}.\\d{1}.\\d{2}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{4}.\\d{1}.\\d{1}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{4}.\\d{2}.\\d{2}\\s\\d{2}:\\d{2}", + "\\d{4}.\\d{2}.\\d{2}\\s\\d{1}:\\d{2}", + "\\d{4}.\\d{1}.\\d{2}\\s\\d{2}:\\d{2}", + "\\d{4}.\\d{1}.\\d{2}\\s\\d{1}:\\d{2}", + "\\d{4}.\\d{2}.\\d{2}\\s\\d{2}", + "\\d{4}.\\d{2}.\\d{2}\\s\\d{1}", + "\\d{4}.\\d{1}.\\d{2}\\s\\d{2}", + "\\d{4}.\\d{1}.\\d{2}\\s\\d{1}", + "\\d{4}/\\d{2}/\\d{2}\\s\\d{2}时\\d{2}分\\d{2}秒", + "\\d{4}/\\d{2}/\\d{2}\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{4}/\\d{1}/\\d{2}\\s\\d{2}时\\d{2}分\\d{2}秒", + "\\d{4}/\\d{1}/\\d{2}\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{4}/\\d{2}/\\d{2}\\s\\d{2}时\\d{2}分", + "\\d{4}/\\d{2}/\\d{2}\\s\\d{1}时\\d{2}分", + "\\d{4}/\\d{1}/\\d{2}\\s\\d{2}时\\d{2}分", + "\\d{4}/\\d{1}/\\d{2}\\s\\d{1}时\\d{2}分", + "\\d{4}/\\d{2}/\\d{2}\\s\\d{2}时", + "\\d{4}/\\d{2}/\\d{2}\\s\\d{1}时", + "\\d{4}/\\d{1}/\\d{2}\\s\\d{2}时", + "\\d{4}/\\d{1}/\\d{2}\\s\\d{1}时", "\\d{4}/\\d{2}/\\d{2}", + "\\d{4}/\\d{2}/\\d{1}", "\\d{4}/\\d{1}/\\d{2}", + "\\d{4}/\\d{1}/\\d{1}", + "\\d{4}/\\d{2}/\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{4}/\\d{2}/\\d{2}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{4}/\\d{1}/\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{4}/\\d{1}/\\d{2}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{4}/\\d{2}/\\d{2}\\s\\d{2}:\\d{2}", + "\\d{4}/\\d{2}/\\d{2}\\s\\d{1}:\\d{2}", + "\\d{4}/\\d{1}/\\d{2}\\s\\d{2}:\\d{2}", + "\\d{4}/\\d{1}/\\d{2}\\s\\d{1}:\\d{2}", + "\\d{4}/\\d{2}/\\d{2}\\s\\d{2}", + "\\d{4}/\\d{2}/\\d{2}\\s\\d{1}", + "\\d{4}/\\d{1}/\\d{2}\\s\\d{2}", + "\\d{4}/\\d{1}/\\d{2}\\s\\d{1}", + "\\d{2}月\\d{2}日\\s\\d{2}时\\d{2}分\\d{2}秒", + "\\d{2}月\\d{2}日\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{1}月\\d{2}日\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{1}月\\d{2}日\\s\\d{2}时\\d{2}分\\d{2}秒", + "\\d{2}月\\d{2}日\\d{2}时\\d{2}分\\d{2}秒", + "\\d{2}月\\d{2}日\\s\\d{2}时\\d{2}分", + "\\d{1}月\\d{2}日\\s\\d{2}时\\d{2}分", + "\\d{1}月\\d{2}日\\s\\d{1}时\\d{2}分", + "\\d{1}月\\d{2}日\\s\\d{2}时\\d{2}分", + "\\d{2}月\\d{2}日\\d{2}时\\d{2}分", "\\d{2}月\\d{2}日\\s\\d{2}时", + "\\d{2}月\\d{2}日\\s\\d{1}时", "\\d{1}月\\d{2}日\\s\\d{2}时", + "\\d{1}月\\d{2}日\\s\\d{1}时", "\\d{2}月\\d{2}日\\d{2}时", + "\\d{4}年\\d{2}月\\d{2}日", "\\d{2}月\\d{1}日", + "\\d{4}年\\d{1}月\\d{2}日", "\\d{1}月\\d{1}日", + "\\d{2}月\\d{2}日\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{2}月\\d{2}日\\s\\d{2}:\\d{1}:\\d{2}", + "\\d{1}月\\d{2}日\\s\\d{2}:\\d{1}:\\d{2}", + "\\d{1}月\\d{2}日\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{2}月\\d{2}日\\d{2}:\\d{2}:\\d{2}", + "\\d{2}月\\d{2}日\\s\\d{2}:\\d{2}", + "\\d{2}月\\d{2}日\\s\\d{1}:\\d{2}", + "\\d{1}月\\d{2}日\\s\\d{2}:\\d{2}", + "\\d{1}月\\d{2}日\\s\\d{1}:\\d{2}", + "\\d{2}月\\d{2}日\\d{2}:\\d{2}", "\\d{2}月\\d{2}日\\s\\d{2}", + "\\d{2}月\\d{2}日\\s\\d{1}", "\\d{1}月\\d{2}日\\s\\d{2}", + "\\d{1}月\\d{2}日\\s\\d{1}", "\\d{2}月\\d{2}日\\d{2}", + "\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{2}-\\d{2}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{1}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{1}-\\d{2}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{2}-\\d{2}\\s\\d{2}:\\d{2}", + "\\d{2}-\\d{2}\\s\\d{1}:\\d{2}", "\\d{2}-\\d{2}\\s\\d{2}", + "\\d{4}-\\d{2}-\\d{2}", "\\d{2}-\\d{1}", + "\\d{4}-\\d{1}-\\d{2}", "\\d{1}-\\d{1}", + "\\d{2}-\\d{2}\\s\\d{2}时\\d{2}分\\d{2}秒", + "\\d{2}-\\d{2}\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{1}-\\d{2}\\s\\d{2}时\\d{2}分\\d{2}秒", + "\\d{1}-\\d{2}\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{1}-\\d{1}\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{2}-\\d{2}\\s\\d{2}时\\d{2}分", + "\\d{2}-\\d{2}\\s\\d{1}时\\d{2}分", + "\\d{1}-\\d{2}\\s\\d{2}时\\d{2}分", + "\\d{1}-\\d{2}\\s\\d{1}时\\d{2}分", "\\d{2}-\\d{2}\\s\\d{2}时", + "\\d{2}-\\d{2}\\s\\d{1}时", "\\d{1}-\\d{2}\\s\\d{2}时", + "\\d{1}-\\d{2}\\s\\d{1}时", "\\d{4}.\\d{2}.\\d{2}", + "\\d{2}.\\d{1}", "\\d{4}.\\d{1}.\\d{2}", "\\d{1}.\\d{1}", + "\\d{2}.\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{2}.\\d{2}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{1}.\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{1}.\\d{2}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{1}.\\d{1}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{2}.\\d{2}\\s\\d{2}:\\d{2}", + "\\d{2}.\\d{2}\\s\\d{1}:\\d{2}", + "\\d{1}.\\d{2}\\s\\d{2}:\\d{2}", + "\\d{1}.\\d{2}\\s\\d{1}:\\d{2}", "\\d{2}.\\d{2}\\s\\d{2}", + "\\d{2}.\\d{2}\\s\\d{1}", "\\d{1}.\\d{2}\\s\\d{2}", + "\\d{1}.\\d{2}\\s\\d{1}", + "\\d{2}/\\d{2}\\s\\d{2}时\\d{2}分\\d{2}秒", + "\\d{2}/\\d{2}\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{1}/\\d{2}\\s\\d{2}时\\d{2}分\\d{2}秒", + "\\d{1}/\\d{2}\\s\\d{1}时\\d{2}分\\d{2}秒", + "\\d{2}/\\d{2}\\s\\d{2}时\\d{2}分", + "\\d{2}/\\d{2}\\s\\d{1}时\\d{2}分", + "\\d{1}/\\d{2}\\s\\d{2}时\\d{2}分", + "\\d{1}/\\d{2}\\s\\d{1}时\\d{2}分", "\\d{2}/\\d{2}\\s\\d{2}时", + "\\d{2}/\\d{2}\\s\\d{1}时", "\\d{1}/\\d{2}\\s\\d{2}时", + "\\d{1}/\\d{2}\\s\\d{1}时", "\\d{2}/\\d{2}", "\\d{2}/\\d{1}", + "\\d{1}/\\d{2}", "\\d{1}/\\d{1}", + "\\d{2}/\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{2}/\\d{2}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{1}/\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", + "\\d{1}/\\d{2}\\s\\d{1}:\\d{2}:\\d{2}", + "\\d{2}/\\d{2}\\s\\d{2}:\\d{2}", + "\\d{2}/\\d{2}\\s\\d{1}:\\d{2}", + "\\d{1}/\\d{2}\\s\\d{2}:\\d{2}", + "\\d{1}/\\d{2}\\s\\d{1}:\\d{2}", "\\d{2}/\\d{2}\\s\\d{2}", + "\\d{2}/\\d{2}\\s\\d{1}", "\\d{1}/\\d{2}\\s\\d{2}", + "\\d{1}/\\d{2}\\s\\d{1}", }; + + String str = ""; + Date date = null; + for (String reg : regs) { + String temp = match(reg, stringTime); + if (temp.length() > str.length()) { + str = temp; + if (!"".equals(str)) { + date = formatDate(str); + } + } + + } + return date; + + } + + /** + * 把String格式的时间转化为date
+ * 支持多种时间格式 + * + * @param stringTime + * @return + */ + public static Date formatDate(String stringTime) { + Date date = null; + if (StringUtils.isNotBlank(stringTime)) { + String[] pattern = new String[] { "yyyy年MM月dd日HH时mm分ss秒", + "yyyy年MM月dd日 HH时mm分ss秒", "yyyy年MM月dd日HH时mm分", + "yyyy年MM月dd日 HH时mm分", "yyyy年MM月dd日 HH时", "yyyy年MM月dd日HH时", + "yyyy年MM月dd日", "yyyy年MM月dd日HH:mm:ss", + "yyyy年MM月dd日 HH:mm:ss", "yyyy年MM月dd日HH:mm", + "yyyy年MM月dd日 HH:mm", "yyyy年MM月dd日 HH", "yyyy年MM月dd日HH", + "yyyy-MM-dd HH时mm分ss秒", "yyyy-MM-dd HH时mm分", + "yyyy-MM-dd HH时", "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", + "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH", + "yyyy/MM/dd HH时mm分ss秒", "yyyy/MM/dd HH时mm分", + "yyyy/MM/dd HH时", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", + "yyyy/MM/dd HH:mm", "yyyy/MM/dd HH", "yyyy.MM.dd HH:mm:ss", + "yyyy.MM.dd HH:mm", "yyyy.MM.dd HH", "yyyy.MM.dd", + "yyyyMMdd", }; + try { + date = DateUtils.parseDate(stringTime, pattern); + } catch (Exception e) { + e.printStackTrace(); + } + } + return date; + + } + + /** + * 提取符合正则表达式的内容 + * + * @param reg + * @param stringTime + * @return + */ + public static String match(String reg, String stringTime) { + Pattern p = Pattern.compile(reg); + Matcher m = p.matcher(stringTime); + String s = ""; + if (m.find()) { + s += m.group(); + } + return s; + } + + /** + * 获取字符编码 + * @param str + * @return + */ + public static String getEncoding(String str) { + String encode; + + encode = "UTF-16"; + try { + if (str.equals(new String(str.getBytes(), encode))) { + return encode; + } + } catch (Exception ex) { + } + + encode = "ASCII"; + try { + if (str.equals(new String(str.getBytes(), encode))) { + return "字符串<< " + str + " >>中仅由数字和英文字母组成,无法识别其编码格式"; + } + } catch (Exception ex) { + } + + encode = "ISO-8859-1"; + try { + if (str.equals(new String(str.getBytes(), encode))) { + return encode; + } + } catch (Exception ex) { + } + + encode = "GB2312"; + try { + if (str.equals(new String(str.getBytes(), encode))) { + return encode; + } + } catch (Exception ex) { + } + + encode = "UTF-8"; + try { + if (str.equals(new String(str.getBytes(), encode))) { + return encode; + } + } catch (Exception ex) { + } + + /* + * ......待完善 + */ + + return "gbk"; + } + + /** + * 把其他格式编码字符串转为utf8 + * @return + */ + public static String toUTF8(String str) { + String rs=""; + try { + String en = getEncoding(str); + rs=new String(str.getBytes(en),"utf-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + + return rs; + } + + //正则找出所有 + public static String getUrl(String s){ + if(s==null||s.length()<1) return null; + String regex = "http[s]?:\\/\\/([\\w]+\\.)+[\\w]+([\\w./?%&=]*)?"; + Pattern pattern = Pattern.compile(regex); + Matcher m = pattern.matcher(s); + String r=""; + while(m.find()){ + r+=m.group()+","; + } + return r; + } + /** + * 将小数保留n位 + * @param d 小数 + * @param n 保留位数 + * @param x 小数为0时是否保留 + * @return + */ + public static String floatToString(double d,int n,boolean x) { + String f="."; + for(int i=0;i getImgStr(String htmlStr,boolean quchong) { + ArrayList pics = new ArrayList<>(); + String img = ""; + Pattern p_image; + Matcher m_image; + String last_img=""; + // String regEx_img = "]*?>"; //图片链接地址 + String regEx_img = "]*?>"; + p_image = Pattern.compile + (regEx_img, Pattern.CASE_INSENSITIVE); + m_image = p_image.matcher(htmlStr); + while (m_image.find()) { + // 得到数据 不懂的qq1023732997 + img = m_image.group(); + // 匹配中的src数据 + Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img); + while (m.find()) { + if(last_img.equals(m.group(1)) && quchong==true) continue; + pics.add(m.group(1)); + last_img=m.group(1); + } + } + return pics; + } + + public static Map urlParamToMaps(String q) { + + if(q==null||"".equals(q.trim())) return null; + String[] a1 = q.split("&"); + if(a1.length>0){ + Map m = new HashMap<>(); + for (String s : a1) { + String[] a2 = s.split("="); + if(a2.length>1){ + m.put(a2[0], a2[1]); + } + } + return m; + } + return null; + } + + + +} diff --git a/src/springmvc-servlet.xml b/src/springmvc-servlet.xml new file mode 100644 index 0000000..679c0be --- /dev/null +++ b/src/springmvc-servlet.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +