提交 a9163d4e authored 作者: 张光耀's avatar 张光耀

修改了商品独立站文件上传,添加了一堆工具类

上级 2b40c07e
package com.platform.controller; package com.platform.controller;
import com.platform.annotation.IgnoreAuth;
import com.platform.entity.TbCfDescripitonEntity; import com.platform.entity.TbCfDescripitonEntity;
import com.platform.entity.TbCfGoodstwotypeEntity; import com.platform.entity.TbCfGoodstwotypeEntity;
import com.platform.entity.TbCfStationItemEntity; import com.platform.entity.TbCfStationItemEntity;
import com.platform.entity.merge.GoodsTypeToGoodsTwo; import com.platform.entity.merge.GoodsTypeToGoodsTwo;
import com.platform.enums.OssFolderNameEnum;
import com.platform.service.TbCfDescripitonService; import com.platform.service.TbCfDescripitonService;
import com.platform.service.TbCfGoodstwotypeService; import com.platform.service.TbCfGoodstwotypeService;
import com.platform.service.TbCfStationItemService; import com.platform.service.TbCfStationItemService;
import com.platform.utils.PageUtils; import com.platform.util.ApiBaseAction;
import com.platform.utils.Query; import com.platform.utils.*;
import com.platform.utils.R; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -30,7 +30,7 @@ import java.util.Map; ...@@ -30,7 +30,7 @@ import java.util.Map;
*/ */
@Controller @Controller
@RequestMapping("tbcfstationitem") @RequestMapping("tbcfstationitem")
public class TbCfStationItemController { public class TbCfStationItemController extends ApiBaseAction {
@Autowired @Autowired
private TbCfStationItemService tbCfStationItemService; private TbCfStationItemService tbCfStationItemService;
@Autowired @Autowired
...@@ -41,6 +41,23 @@ public class TbCfStationItemController { ...@@ -41,6 +41,23 @@ public class TbCfStationItemController {
private Long INIT_NUM = 0L; private Long INIT_NUM = 0L;
private Long COUNT_NUM = 1L; private Long COUNT_NUM = 1L;
/**
* 上传文件
*/
@ApiOperation(value = "上传文件", notes = "上传文件")
@ApiImplicitParam(paramType = "query", name = "file", value = "文件", required = true, dataType = "MultipartFile")
@PostMapping("/image")
public Object uploadByUtil(@RequestParam("file") MultipartFile file) throws Exception {
if (file.isEmpty()) {
throw new RRException("上传文件不能为空");
}
//上传文件
String url = OssUtil.upload(file, OssFolderNameEnum.STATION.getValue());
return toResponsSuccess(url);
}
/** /**
* 查看列表 * 查看列表
*/ */
......
package com.platform.controller.api;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.platform.utils.OssUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.aliyun.oss.OSSClient;
import com.platform.annotation.IgnoreAuth;
import com.platform.utils.R;
import com.platform.utils.util.ImageUploadResult;
import com.platform.utils.OssUtil;
import com.platform.utils.util.PageData;
import com.platform.utils.util.StringUtil;
import com.platform.utils.util.UuidUtil;
@Controller
@RequestMapping(value="/api/osstest",produces="application/json;charset=UTF-8")
public class OssTestApi {
@IgnoreAuth
@RequestMapping("/createfolder")
@ResponseBody
public String createFolder() {
try {
OSSClient client= OssUtil.getOSSClient();
String fileDir=OssUtil.createFolder(client, "diaosaas-prod", "xinlizixun/");
return fileDir;
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
@IgnoreAuth
@RequestMapping(value="/uploadtest",produces="application/json;charset=UTF-8")
@ResponseBody
public String upload(MultipartFile file,String secondaryFolderName) {
try {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件后缀
String prefix=fileName.substring(fileName.lastIndexOf("."));
// 用uuid作为文件名,防止生成的文件重复
final File mfile = File.createTempFile(UuidUtil.get32UUID(), prefix);
// MultipartFile to File
file.transferTo(mfile);
String url=OssUtil.uploadObject2OSS(mfile,secondaryFolderName);
System.out.println(mfile.getName());
System.out.println(url);
return url;
} catch (Exception e) {
e.printStackTrace();
return "err";
}
}
@IgnoreAuth
@RequestMapping(value="/uploadfile",produces="application/json;charset=UTF-8")
@ResponseBody
public String uploadfile(MultipartFile file,String secondaryFolderName) {
try {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件后缀
String prefix=fileName.substring(fileName.lastIndexOf("."));
// 用uuid作为文件名,防止生成的文件重复
final File mfile = File.createTempFile(UuidUtil.get32UUID(), prefix);
// MultipartFile to File
file.transferTo(mfile);
String url=OssUtil.uploadObject2OSS(mfile,secondaryFolderName);
System.out.println(mfile.getName());
System.out.println(url);
return url +" "+fileName;
//return "";
} catch (Exception e) {
e.printStackTrace();
return "err";
}
}
/**
*
* @Function: uploadfileVideo
* @Description: (此方法只用于[课程管理模块]上传课程宣传视频和课程视频)
* @param:
* @return:
* @since JDK 1.8
@IgnoreAuth
@RequestMapping(value="/uploadfileVideo",produces="application/json;charset=UTF-8")
@ResponseBody
public Map<String, Object> uploadfileVideo(HttpServletRequest request,MultipartFile[] files) {
Map<String, Object> map = new HashMap<>();
List<String> urlList = new ArrayList<>();
try {
for (int i = 0; i < files.length; i++) {
// 获取文件名
String fileName = files[i].getOriginalFilename();
// 获取文件后缀
String prefix=fileName.substring(fileName.lastIndexOf("."));
System.out.println(UuidUtil.get32UUID()+"-"+fileName.substring(0,fileName.lastIndexOf(".")));
final File mfile = File.createTempFile(UuidUtil.get32UUID(), prefix);
// MultipartFile to File
files[i].transferTo(mfile);
String url=OssUtil.uploadObject3OSS(mfile,fileName);
// String fileUpload = OssUtil.fileUpload(mfile, fileName, request);
System.out.println(mfile.getName());
urlList.add(url);
// urlList.add(fileUpload);
}
map.put("urlList", urlList);
return map;
} catch (Exception e) {
e.printStackTrace();
return map;
}
} */
@IgnoreAuth
@RequestMapping("/deletetest")
@ResponseBody
public R delete(String url) {
try {
// http://diaosaas-prod.oss-cn-shenzhen.aliyuncs.com/education/155771122620710111.jpg
url = url.substring(url.lastIndexOf("/")+1);
OssUtil.deleteFile("diaosaas-prod", "education/", url);
return R.ok().put("success", "删除成功");
} catch (Exception e) {
e.printStackTrace();
return R.error().put("fail", "删除失败");
}
}
/**
* 富文本图片自定义上传
*/
@IgnoreAuth
@RequestMapping(value="/uploaditemimage",produces="application/json;charset=UTF-8")
@ResponseBody
public Object uploadItemImage(HttpServletRequest request) throws Exception {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile photo = multipartRequest.getFile("upfile");
String url = "";
if (photo.getSize() > 0) {
String result =OssUtil.upload(photo);
if (result.equals("fail")) {
} else {
url = result;
}
}
// 这里获取到文件 处理上传后返回路径
ImageUploadResult result = new ImageUploadResult();
result.setState("SUCCESS");
result.setUrl(url);
result.setOriginal(System.currentTimeMillis() + "/" + photo.getOriginalFilename());
result.setTitle(photo.getOriginalFilename());
return result;
}
// 删除富文本的图片
//content 需要更新的内容
//pd 没更新的数据
public void deleteUeditorImg( String content,PageData pd) {
if(pd.get("describes")!=null&&pd.get("describes").toString().trim().length()>0 ){
String dbContent = pd.getString("describes");
List<String> list = StringUtil.getImgStr(dbContent);
String[] a = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
a[i] = list.get(i);
}
List<String> list1 = StringUtil.getImgStr(content);
String[] b = new String[list1.size()];
for (int i = 0; i < list1.size(); i++) {
b[i] = list1.get(i);
}
List<String> list2 = StringUtil.compare(b, a);
for (int i = 0; i < list2.size(); i++) {
String path = list2.get(i);
path.substring(path.lastIndexOf("/")+1, path.length());
OssUtil.deleteFile("diaosaas-prod", "education/", path);
}
}
}
/**
* 获取实时长传进度
* @param request
* @return
*/
@RequestMapping ("/item/percent")
@ResponseBody
public int getUploadPercent(HttpServletRequest request){
HttpSession session = request.getSession();
int percent = session.getAttribute("upload_percent") == null ? 0: (Integer)session.getAttribute("upload_percent");
return percent;
}
/**
* 重置上传进度
* @param request
* @return
*/
@RequestMapping ("/percent/reset")
public void resetPercent(HttpServletRequest request){
HttpSession session = request.getSession();
session.setAttribute("upload_percent",0);
}
/**多线程分片文件上传**/
@RequestMapping("uploadFile")
public String uploadBlog(@RequestParam("file")MultipartFile file,HttpServletRequest request){//MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称。 logger.info("文件上传");
HttpSession session=request.getSession();
String filename=file.getOriginalFilename();
session.setAttribute("fileName",filename);
System.out.println(filename);
long fileLength=file.getSize();
DecimalFormat df=new DecimalFormat(".00");
if(fileLength<1024){
session.setAttribute("fileSize","1KB");
}else if(fileLength>=1024 && fileLength<1024*1024){
session.setAttribute("fileSize",df.format(fileLength/1024.0)+"KB");
}else {
session.setAttribute("fileSize",df.format(fileLength/(1024.0*1024.0))+"MB");
}
try {
if(file!=null){
if (!"".equals(filename.trim())){
//MultipartFile转File
File newFile=new File(filename);
FileOutputStream os=new FileOutputStream(newFile);
os.write(file.getBytes());
os.close();
file.transferTo(newFile);//将上传文件写入目标文件
//上传到OSS
String key="time1128";
// String url=OssUtil.upLoad(newFile,session,key);
//删除临时文件
newFile.delete();
}
}
} catch (Exception e) {
e.printStackTrace();
//return "上传失败:"+e.getMessage();
}
return "upload_success";//上传成功页面
}
}
<!DOCTYPE html> <!DOCTYPE html>
<html> <html xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head> <head>
<title>站点商品</title> <title>站点商品</title>
#parse("sys/header.html") #parse("sys/header.html")
...@@ -45,12 +45,32 @@ ...@@ -45,12 +45,32 @@
<Form-item label="商品链接" prop="itemUrl"> <Form-item label="商品链接" prop="itemUrl">
<i-input v-model="tbCfStationItem.itemUrl" placeholder="商品链接"/> <i-input v-model="tbCfStationItem.itemUrl" placeholder="商品链接"/>
</Form-item> </Form-item>
<Form-item label="商品价格" prop="itemUrl"> <Form-item label="商品价格" prop="itemPrice">
<i-input v-model="tbCfStationItem.itemPrice" placeholder="商品价格"/> <i-input v-model="tbCfStationItem.itemPrice" placeholder="商品价格"/>
</Form-item> </Form-item>
<Form-item label="商品图片" prop="itemImg">
<!-- <i-input v-model="xPicture.pictureUrl" placeholder="图片地址"/> -->
<upload
action="../api/osstest/uploadtest"
:before-upload="handleBeforeUpload"
:on-success="handleSuccess" :show-upload-list="false" accept="image/jpeg, image/png">
<i-button icon="ios-cloud-upload-outline">请选择图片</i-button>
</upload>
<div style="display: flex;position: relative;">
<div v-for="item in uploadList" style="margin-left: 5px;">
<img :src="item" width="100" height="100" id="itemImg">
<i class="ivu-icon ivu-icon-ios-trash-outline" style="cursor:pointer;display: flex;font-size: 24px;position: relative;left:11" @click="delImg1(item)"></i>
</div>
</div>
</Form-item>
<!--
<Form-item label="商品图片" prop="itemImg"> <Form-item label="商品图片" prop="itemImg">
<i-input v-model="tbCfStationItem.itemImg" placeholder="商品图片"/> <img v-bind:src="tbCfStationItem.itemImg" style="width:200px;height:200px;" v-show="!!tbCfStationItem.itemImg"/>
<input type="file" placeholder="商品图片" @change="tirggerFile($event)"/>
</Form-item> </Form-item>
-->
<Form-item label="所属平台" prop="platformCode"> <Form-item label="所属平台" prop="platformCode">
<i-input v-model="tbCfStationItem.platformCode" placeholder="所属平台"/> <i-input v-model="tbCfStationItem.platformCode" placeholder="所属平台"/>
</Form-item> </Form-item>
......
...@@ -28,6 +28,7 @@ let vm = new Vue({ ...@@ -28,6 +28,7 @@ let vm = new Vue({
tbCfStationItem: {}, tbCfStationItem: {},
Goodstype:null, Goodstype:null,
Goodstype2:null, Goodstype2:null,
uploadList : [],
Goodstype3:null, Goodstype3:null,
ruleValidate: { ruleValidate: {
name: [ name: [
...@@ -41,34 +42,32 @@ let vm = new Vue({ ...@@ -41,34 +42,32 @@ let vm = new Vue({
methods: { methods: {
//获取一级分类 //获取一级分类
changeGoodstype(){ changeGoodstype(){
let url = `/africa_shop/tbcfstationitem/queryByItemType?typeId=${this.tbCfStationItem.itemCategory}` // console.log(this.tbCfStationItem.itemCategory);
//console.log('url',url) let url = "../tbcfstationitem/queryByItemType?typeId="+this.tbCfStationItem.itemCategory;
// console.log('url',url)
let that = this; let that = this;
Ajax.request({ Ajax.request({
url: url, url: url,
type: "get", type: "get",
contentType: "application/json", contentType: "application/json",
successCallback: function (r) { successCallback: function (r) {
console.log('res',r)
if(r.code===0){ if(r.code===0){
that.Goodstype2 = r.list that.Goodstype2 = r.list
console.log(that.Goodstype2)
} }
} }
}); });
}, },
changeGoodstype2(){ changeGoodstype2(){
let url = `/africa_shop/tbcfstationitem/queryByItemTypeTwo?typeTwoId=${this.tbCfStationItem.itemCategorytwo}` let url = "../tbcfstationitem/queryByItemTypeTwo?typeTwoId="+this.tbCfStationItem.itemCategorytwo;
let that = this; let that = this;
Ajax.request({ Ajax.request({
url: url, url: url,
type: "get", type: "get",
contentType: "application/json", contentType: "application/json",
successCallback: function (r) { successCallback: function (r) {
console.log('res',r)
if(r.code===0){ if(r.code===0){
that.Goodstype3 = r.descripiton that.Goodstype3 = r.descripiton
console.log(that.Goodstype3)
} }
} }
}); });
...@@ -92,6 +91,7 @@ let vm = new Vue({ ...@@ -92,6 +91,7 @@ let vm = new Vue({
vm.getInfo(itemId); vm.getInfo(itemId);
}, },
saveOrUpdate: function (event) { saveOrUpdate: function (event) {
vm.tbCfStationItem.itemImg = vm.uploadList[0];
let url = vm.tbCfStationItem.itemId == null ? "../tbcfstationitem/save" : "../tbcfstationitem/update"; let url = vm.tbCfStationItem.itemId == null ? "../tbcfstationitem/save" : "../tbcfstationitem/update";
Ajax.request({ Ajax.request({
url: url, url: url,
...@@ -131,6 +131,7 @@ let vm = new Vue({ ...@@ -131,6 +131,7 @@ let vm = new Vue({
async: true, async: true,
successCallback: function (r) { successCallback: function (r) {
vm.tbCfStationItem = r.tbCfStationItem; vm.tbCfStationItem = r.tbCfStationItem;
vm.uploadList[0] = vm.tbCfStationItem.itemImg;
} }
}); });
}, },
...@@ -156,7 +157,105 @@ let vm = new Vue({ ...@@ -156,7 +157,105 @@ let vm = new Vue({
}, },
handleReset: function (name) { handleReset: function (name) {
handleResetForm(this, name); handleResetForm(this, name);
} },
/*
tirggerFile : function (event) {
var file = event.target.files[0]; // (利用console.log输出看file文件对象)
var formData = new FormData();
formData.append("file", file);
$.ajax({
url: "../tbcfstationitem/image/",
type: "POST",
data: formData,
cache: false, //不设置缓存
processData: false, // 不处理数据
contentType: false,// 不设置内容类型
success: function (result) {
result = JSON.parse(result);
console.log(result)
if (result.errno == 0) {//成功
vm.tbCfStationItem.itemImg = result.data;
console.log(vm.tbCfStationItem.itemImg)
vm.$forceUpdate();
} else {
iview.Message.error(result.errmsg);
}
}
});
}*/
/** ******************************************************************************************** */
handleSuccess (response, file, fileList) {
// "http://diaosaas-prod.oss-cn-shenzhen.aliyuncs.com/education/155728894307110106.jpg"
vm.uploadList.push(response);
$("#itemImg").show();
},
handleBeforeUpload (file) {
// 上传图片大小不超过5M
if (file.size > 5 * 1024 * 1024 ) {
alert('请上传不超过5M的图片');
return false;
}
const check = this.uploadList.length < 1;
if (!check) {
this.$Notice.warning({
title: '最多只能上传一张图片'
});
return false;
}
// 限制上传文件的宽高
// return this.checkImageWH(file,750,320);
},
// 限制上传图片的宽高
checkImageWH : function(file, width, height) {
let self = this;
return new Promise(function (resolve, reject) {
let filereader = new FileReader();
filereader.onload = e => {
console.log("2222");
let src = e.target.result;
const image = new Image();
image.onload = function () {
if (width && image.width != width) {
self.$Notice.error({
title: '请上传宽为' + width + "的图片",
});
reject();
} else if (height && image.height != height) {
self.$Notice.error({
title: '请上传高为' + height + "的图片",
});
reject();
} else {
resolve();
}
};
image.onerror = reject;
image.src = src;
};
filereader.readAsDataURL(file);
});
},
// 删除上传图片
delImg1:function(url){
if (vm.title != "详情") {
vm.uploadList.remove(url);
console.log(url);
Ajax.request({
url: "../api/osstest/deletetest?url="+url,
async: false,
type: "POST",
contentType: "application/json",
successCallback: function (resultData) {
// console.log(resultData);
iview.Message.success(resultData.success);
}
});
}
},
/** ******************************************************************************************** */
}, },
created(){ created(){
var that = this var that = this
......
...@@ -139,5 +139,93 @@ ...@@ -139,5 +139,93 @@
<artifactId>jgroups</artifactId> <artifactId>jgroups</artifactId>
<version>${jgroups.version}</version> <version>${jgroups.version}</version>
</dependency> </dependency>
<!-- 我自己添加的 -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.apache.axis</groupId>
<artifactId>axis</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<!-- emoji -->
<groupId>com.vdurmont</groupId>
<artifactId>emoji-java</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>java-emoji-converter</artifactId>
<version>0.1.1</version>
</dependency>
<!-- 跨服务器文件上传 -->
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-client -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>
<!--QRCode -->
<dependency>
<groupId>QRCode</groupId>
<artifactId>QRCode</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>sun.misc</groupId>
<artifactId>sun.misc</artifactId>
<version>1.0</version>
</dependency>
<!-- 二维码生成工具 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.1</version>
</dependency>
<!-- 富文本编辑器 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>json</groupId>
<artifactId>json</artifactId>
<version>0.1</version>
</dependency>
<dependency>
<groupId>ueditor</groupId>
<artifactId>ueditor</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file
...@@ -9,7 +9,9 @@ package com.platform.enums; ...@@ -9,7 +9,9 @@ package com.platform.enums;
public enum OssFolderNameEnum implements EnumItemable<OssFolderNameEnum> { public enum OssFolderNameEnum implements EnumItemable<OssFolderNameEnum> {
HOMEPAGE("首页", "homePage"), HOMEPAGE("首页", "homePage"),
STATION("商品独立站","stationItem"),
PROBLEM("问题", "problem"); PROBLEM("问题", "problem");
private String label; private String label;
private String value; private String value;
......
package com.platform.utils;
import java.util.UUID;
public class UuidUtil {
public static String get32UUID() {
String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
return uuid;
}
public static void main(String[] args) {
System.out.println(get32UUID());
}
}
package com.platform.utils.util;
import org.apache.commons.codec.binary.Base64;
//import Decoder.BASE64Encoder;
import java.io.*;
/**
* @author shkstart
* @create 2019-02-22-下午 4:47
* File和byte[]转换
*/
public class ByteAndFile {
/*
public static byte[] File2byte(String filePath)
{
byte[] buffer = null;
try
{
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1)
{
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return buffer;
}
*/
/*
public static File byte2File(byte[] buf, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {
dir.mkdirs();
}
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(buf);
return file;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}*/
/**
* 将输入流转为base64图片
* @author LHB
* @since JDK 1.8
* <img src=“data:image/png;base64,***************************************************"/>
public static String getBase64FromInputStream(InputStream in) {
// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;
// 读取图片字节数组
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = in.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String string = new String(Base64.encodeBase64(data));
return "data:image/png;base64,"+string;
} */
/**
* 将输入流转为base64图片
* @author LHB
* @since JDK 1.8
* <img src=“data:image/png;base64,***************************************************"/>
*
* 没用过
public static <BASE64Encoder> String getImageStrFromPath(String url) {
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
in = FileDownload.getImageStream(url);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return encoder.encode(data);
} */
}
package com.platform.utils.util;
import org.springframework.context.ApplicationContext;
/**
* 项目名称:
*/
public class Const {
public static final String SESSION_SECURITY_CODE = "sessionSecCode"; //验证码
public static final String SESSION_USER = "sessionUser"; //session用的用户
public static final String SESSION_ROLE_RIGHTS = "sessionRoleRights";
public static final String sSESSION_ROLE_RIGHTS = "sessionRoleRights";
public static final String SESSION_menuList = "menuList"; //当前菜单
public static final String SESSION_allmenuList = "allmenuList"; //全部菜单
public static final String SESSION_QX = "QX";
public static final String SESSION_userpds = "userpds";
public static final String SESSION_USERROL = "USERROL"; //用户对象
public static final String SESSION_USERNAME = "USERNAME"; //用户名
public static final String DEPARTMENT_IDS = "DEPARTMENT_IDS"; //当前用户拥有的最高部门权限集合
public static final String DEPARTMENT_ID = "DEPARTMENT_ID"; //当前用户拥有的最高部门权限
public static final String TRUE = "T";
public static final String FALSE = "F";
public static final String BANKINFO = "admin/config/BANKINFO.txt"; //银行卡号查询文档
public static final String LOGIN = "/login_toLogin.do"; //登录地址
public static final String SYSNAME = "admin/config/SYSNAME.txt"; //系统名称路径
public static final String PAGE = "admin/config/PAGE.txt"; //分页条数配置路径
public static final String EMAIL = "admin/config/EMAIL.txt"; //邮箱服务器配置路径
public static final String SMS1 = "admin/config/SMS1.txt"; //短信账户配置路径1
public static final String SMS2 = "admin/config/SMS2.txt"; //短信账户配置路径2
public static final String FWATERM = "admin/config/FWATERM.txt"; //文字水印配置路径
public static final String IWATERM = "admin/config/IWATERM.txt"; //图片水印配置路径
public static final String WEIXIN = "admin/config/WEIXIN.txt"; //微信配置路径
public static final String WEBSOCKET = "admin/config/WEBSOCKET.txt"; //WEBSOCKET配置路径
public static final String LOGINEDIT = "admin/config/LOGIN.txt"; //登录页面配置
public static final String FILEPATHIMG = "uploadFiles/uploadImgs/"; //图片上传路径
public static final String FILEPATHFILE = "uploadFiles/file/"; //文件上传路径
public static final String FILEPATHFILEOA = "uploadFiles/uploadFile/"; //文件上传路径(oa管理)
public static final String FILEPATHTWODIMENSIONCODE = "uploadFiles/twoDimensionCode/"; //二维码存放路径
public static final String NO_INTERCEPTOR_PATH = ".*/((login)|(logout)|(code)|(app)|(weixin)|(static)|(main)|(api)|(websocket)|(uploadImgs)).*"; //不对匹配该值的访问路径拦截(正则)
public static ApplicationContext WEB_APP_CONTEXT = null; //该值会在web容器启动时由WebAppContextListener初始化
/**
* APP Constants
*/
//系统用户注册接口_请求协议参数)
public static final String[] SYSUSER_REGISTERED_PARAM_ARRAY = new String[]{"USERNAME","PASSWORD","NAME","EMAIL","rcode"};
public static final String[] SYSUSER_REGISTERED_VALUE_ARRAY = new String[]{"用户名","密码","姓名","邮箱","验证码"};
//app根据用户名获取会员信息接口_请求协议中的参数
public static final String[] APP_GETAPPUSER_PARAM_ARRAY = new String[]{"USERNAME"};
public static final String[] APP_GETAPPUSER_VALUE_ARRAY = new String[]{"用户名"};
}
package com.platform.utils.util;
/**
* 说明:
* @version
*/
public class Constants {
public static String PICTURE_VISIT_FILE_PATH = "";//图片访问的路径
public static String PICTURE_SAVE_FILE_PATH = "";//图片存放的路径
public static String getPICTURE_VISIT_FILE_PATH() {
return PICTURE_VISIT_FILE_PATH;
}
public static void setPICTURE_VISIT_FILE_PATH(String pICTURE_VISIT_FILE_PATH) {
PICTURE_VISIT_FILE_PATH = pICTURE_VISIT_FILE_PATH;
}
public static String getPICTURE_SAVE_FILE_PATH() {
return PICTURE_SAVE_FILE_PATH;
}
public static void setPICTURE_SAVE_FILE_PATH(String pICTURE_SAVE_FILE_PATH) {
PICTURE_SAVE_FILE_PATH = pICTURE_SAVE_FILE_PATH;
}
public static void main(String[] args) {
Constants.setPICTURE_SAVE_FILE_PATH("D:/Tomcat 6.0/webapps/FH/topic/");
Constants.setPICTURE_VISIT_FILE_PATH("http://192.168.1.225:8888/FH/topic/");
}
}
package com.platform.utils.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
*
* <p>
* 时间转换工具类
* </p>
*
* @ClassName: DateHelper
* @author: fandonghong
* @date 2016-11-22 上午09:48:59
*
*/
public class DateHelper {
public final static SimpleDateFormat g_SimpleDateFormat = new SimpleDateFormat("yyyyMMdd");
public final static SimpleDateFormat g_SimpleDateFormat_I = new SimpleDateFormat("yyyy-MM-dd");
public final static SimpleDateFormat g_SimpleDateFormat_II = new SimpleDateFormat("yyyyMM");
public final static SimpleDateFormat sdfDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public final static SimpleDateFormat sdfDateTimeFormat_I = new SimpleDateFormat("yyyyMMddHHmmss");
public final static SimpleDateFormat sdfDateTimeFormat_IIII = new SimpleDateFormat("HH:mm:ss");
public final static SimpleDateFormat sdfDateTimeFormat_YYYY = new SimpleDateFormat("yyyy");
public final static SimpleDateFormat x_dateTimeFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
public final static SimpleDateFormat xISO_dateTimeFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z");
/**
* 获取当前日期
*
* @return
*/
public static Date getCurrentDate() {
Calendar calendar = Calendar.getInstance();
return calendar.getTime();
}
/**
* 返回当前时间日期格式(yyyyMMddHHmmss)
*
* @return
*/
public static String getCurDateTime() {
Calendar now = Calendar.getInstance(TimeZone.getDefault());
String DATE_FORMAT = "yyyyMMddHHmmss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getDefault());
return (sdf.format(now.getTime()));
}
/**
* 返回日期格式(yyyy-MM-dd HH:mm:ss)
*
* @param object
* @return
*/
public static String getDateTime(Object object) {
return sdfDateTimeFormat.format(object);
}
/**
* 返回日期格式(yyyyMMdd)
*
* @param date
* @return
*/
public static String getDateTime2(Date date) {
return g_SimpleDateFormat.format(date);
}
/**
* 返回日期格式(yyyy-MM-dd)
*
* @param date
* @return
*/
public static String getDateTime_I(Date date) {
return g_SimpleDateFormat_I.format(date);
}
/**
* 返回日期格式(yyyy-MM-dd HH:mm:ss)
*
* @param date
* @return
*/
public static String getDateTime_III(Date date) {
return sdfDateTimeFormat.format(date);
}
/**
* <p>
* 返回日期格式(yyyy-MM-dd HH:mm:ss)
* </p>
* <br>
*
* @return
*/
public static String getCurrDateTime() {
return sdfDateTimeFormat.format(new Date());
}
/**
* 返回时间格式(HH:mm:ss)
*
* @param date
* @return
*/
public static String getDateTime_IIII(Date date) {
return sdfDateTimeFormat_IIII.format(date);
}
/**
* 返回日期格式(yyyyMMddHHmmss)
*
* @param date
* @return
*/
public static String getDateTime_IV(Date date) {
return sdfDateTimeFormat_I.format(date);
}
/**
* 获取当前日期(yyyyMMdd)
*
* @return
*/
public static String getCurDate() {
return g_SimpleDateFormat.format(new Date());
}
/**
* <p>
* 获取当前系统时间的小时数
* </p>
*
* @return
*/
public static int getCurrentHour() {
Calendar calendar = new GregorianCalendar();
return calendar.get(Calendar.HOUR_OF_DAY);
}
/**
* 得到当前时间分钟
*
* @return
*/
public static int getCurrentMinute() {
Calendar calendar = new GregorianCalendar();
return calendar.get(Calendar.MINUTE);
}
/**
* <p>
* 获取当前年月格式(yyyyMM)
* </p>
*
* @return
*/
public static String getCurrentMonth() {
Calendar calendar = new GregorianCalendar();
return g_SimpleDateFormat_II.format(calendar.getTime());
}
public static String getMonth(Date date) {
return g_SimpleDateFormat_II.format(date);
}
/**
*
* 获得本月的前(后)几个月。(yyyyMM)
* <p>
* %方法详述(简单方法可不必详述)%。
* </p>
*
* @param month 月数字(数字大于1为后,小于1为前)
* @return
*/
public static String getBAMonth(int monthNum) {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.MONTH, monthNum);
return g_SimpleDateFormat_II.format(calendar.getTime());
}
/**
* <p>
* 获取本月第一天日期(格式如YYYYMMDD),如果当前日为当月1日,则返回上月第一日
* </p>
*
* @return
*/
public static String getMonthFirstDay() {
Calendar calendar = new GregorianCalendar();
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = 0;
if (day == 1)// 当月第一日
{
calendar.add(Calendar.MONTH, -1);
}
month = calendar.get(Calendar.MONTH);
if (month < 10) {
return "" + calendar.get(Calendar.YEAR) + "0" + (month + 1) + "01";
} else {
return "" + calendar.get(Calendar.YEAR) + (month + 1) + "01";
}
}
/**
* <p>
* 获取当前时间前几天或后几天的日期
* </p>
* 日数字(数字大于1为后,小于1为前)
*
* @return
*/
public static Date getAddDays(int days) {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.DAY_OF_YEAR, days);
return calendar.getTime();
}
/**
* <p>
* 获取某个月后的日期格式(yyyyMMdd)
* </p>
*
* @return
*/
public static String getAfterMonth(int monthNum) {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.MONTH, monthNum);
return g_SimpleDateFormat.format(calendar.getTime());
}
/**
* <p>
* 返回日期(格式yyyyMMdd)
* </p>
*
* @param timeMillis
* @return
*/
public static String getFormatDate(long timeMillis) {
return sdfDateTimeFormat_I.format(new Date(timeMillis));
}
/**
* 获取当前系统时间距离传入时间的毫秒数
*
* @param strTime 格式[ DD:00:00]
* @return
* @throws ParseException
*/
public static long getSleepTime(String strTime) throws ParseException {
long p = 1;
long l_date = System.currentTimeMillis();
Date date_now = new Date(l_date);
String strDate = g_SimpleDateFormat_I.format(date_now) + strTime;
if (date_now.before(sdfDateTimeFormat.parse(strDate)))
p = (sdfDateTimeFormat.parse(strDate)).getTime() - l_date;
else {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date_now);
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date date = calendar.getTime();
strDate = g_SimpleDateFormat_I.format(date) + strTime;
p = (sdfDateTimeFormat.parse(strDate)).getTime() - l_date;
}
return p;
}
/**
* 返回当前日期的前一天 返回格式(YYYY-mm-dd)
*
* @return
*/
public static String getPredate() {
Date nowDate = new Date();
String nowdates = g_SimpleDateFormat_I.format(nowDate);
String[] dates = nowdates.split("-");
int year = Integer.parseInt(dates[0]);
int month = Integer.parseInt(dates[1]);
int day = Integer.parseInt(dates[2]) - 1;
if (day == 0) {
switch (month - 1) {
case 1:
day = 31;
break;
case 3:
day = 31;
break;
case 5:
day = 31;
break;
case 7:
day = 31;
break;
case 8:
day = 31;
break;
case 10:
day = 31;
break;
case 0:
month = 13;
year = year - 1;
day = 31;
break;
case 4:
day = 30;
break;
case 6:
day = 30;
break;
case 9:
day = 30;
break;
case 11:
day = 30;
break;
case 2:
if (year % 4 == 0) {
day = 29;
} else {
day = 28;
}
break;
default:
break;
}
month = month - 1;
}
String predate = Integer.toString(year) + "-" + (month < 10 ? "0" + month : month) + "-"
+ (day < 10 ? "0" + day : day);
return predate;
}
/**
* add by hushiwang
* <p>
* 得到xxxx年xx月xx日 日期格式。
* </p>
*
* @param date
* @return
*/
public static String getChinaDateFormat(Date date) {
// 得到yyyy-mm-dd格式日期格式
String dateStr = getDateTime_I(date);
StringBuffer sb = new StringBuffer();
if (dateStr != null && dateStr.length() > 0) {
String[] newStr = dateStr.split("-");
// 得到月
Integer month = Integer.valueOf(newStr[1]);
// 得到日
Integer day = Integer.valueOf(newStr[2]);
sb.append(newStr[0]).append("年");
sb.append(month).append("月").append(day).append("日");
}
return sb.toString();
}
/**
* add by wangzs
* <p>
* 得到xxxx年xx月xx日xx时xx分日期格式。
* </p>
*
* @param date
* @return
*/
public static String getChinaDateFormat_II(Date date) {
// 得到yyyy-mm-dd HH:mm:ss格式日期格式
String dateStr = getDateTime(date);
StringBuffer sb = new StringBuffer();
if (dateStr != null && dateStr.length() > 0) {
String[] str = dateStr.split(" ");
if (str != null && str.length > 1) {
String[] newStr = str[0].split("-");
// 得到月
Integer month = Integer.valueOf(newStr[1]);
// 得到日
Integer day = Integer.valueOf(newStr[2]);
sb.append(newStr[0]).append("年");
sb.append(month).append("月").append(day).append("日");
String[] newStr_II = str[1].split(":");
sb.append(newStr_II[0]).append("时").append(newStr_II[1]).append("分");
}
}
return sb.toString();
}
/**
* add by hushiwang
* <p>
* 得到xxxx年xx月xx日 日期格式。
* </p>
*
* @param date 格式必须是2009-03-21字符串
* @return
*/
public static String getChinaDateFormat(String date) {
// 得到yyyy-mm-dd格式日期格式
StringBuffer sb = new StringBuffer();
if (date != null && date.length() > 0) {
String[] newStr = date.split("-");
// 得到月
Integer month = Integer.valueOf(newStr[1]);
// 得到日
Integer day = Integer.valueOf(newStr[2]);
sb.append(newStr[0]).append("年");
sb.append(month).append("月").append(day).append("日");
}
return sb.toString();
}
/**
* 判断一个日期字符串是否合法
*
* @param date
* @param format
* @return
*
*/
public static boolean isDateStringCorrect(String date, String format) {
SimpleDateFormat df = new SimpleDateFormat(format);
try {
df.setLenient(false);
df.parse(date);
return true;
} catch (Exception e) {
return false;
}
}
/**
*
* <P>
* 将字符串类型的日期格式 转换为 符合要求的日期格式
* </P>
*
* @param date
* @param format
* @return
*/
public static String getStrDate4String(String date, String format) {
if (date == null || date.trim().equals("")) {
return "";
} else {
SimpleDateFormat df = new SimpleDateFormat(format);
try {
Date d = df.parse(date);
return df.format(d);
} catch (ParseException e) {
System.out.println(e);
return "";
}
}
}
/**
*
* <P>
* 将Date类型的日期格式 转换为 符合要求的 String日期格式
* </P>
*
* @param date
* @param format
* @return
*/
public static String getStrDate4Date(Date date, String format) {
if (date == null) {
return "";
} else {
SimpleDateFormat df = new SimpleDateFormat(format);
return df.format(date);
}
}
/**
*
* <P>
* 将字符串类型的日期格式 转换为 符合要求的 Date类型的日期格式
* </P>
*
* @param date
* @param format
* @return
*/
public static Date getDate4StrDate(String date, String format) {
if (date == null || date.trim().equals("")) {
return null;
} else {
SimpleDateFormat df = new SimpleDateFormat(format);
try {
return df.parse(date);
} catch (ParseException e) {
return null;
}
}
}
/**
* 计算指定日期时间之间的时间差
*
* @param beginStr
* 开始日期字符串
* @param endStr
* 结束日期字符串
* @param f
* 时间差的形式0-秒,1-分种,2-小时,3--天 日期时间字符串格式:yyyyMMddHHmmss
*/
public static int getInterval(String beginStr, String endStr, int f) {
int hours = 0;
try {
Date beginDate = sdfDateTimeFormat.parse(beginStr);
Date endDate = sdfDateTimeFormat.parse(endStr);
long millisecond = endDate.getTime() - beginDate.getTime(); // 日期相减得到日期差X(单位:毫秒)
/**
* Math.abs((int)(millisecond/1000)); 绝对值 1秒 = 1000毫秒
* millisecond/1000 --> 秒 millisecond/1000*60 - > 分钟
* millisecond/(1000*60*60) -- > 小时 millisecond/(1000*60*60*24) -->
* 天
*/
switch (f) {
case 0: // second
return (int) (millisecond / 1000);
case 1: // minute
return (int) (millisecond / (1000 * 60));
case 2: // hour
return (int) (millisecond / (1000 * 60 * 60));
case 3: // day
return (int) (millisecond / (1000 * 60 * 60 * 24));
}
} catch (Exception e) {
e.printStackTrace();
}
return hours;
}
/**
*
* <P>
* 得到起始日期前或后天数的日期
* </P>
*
* @param starttime
* 起始日期 格式:yyyy-MM-dd
* @param days
* @return
* @throws ParseException
*/
public static Date getStartDateInterval(String starttime, int days) {
// 格式化起始时间 yyyyMMdd
Date startDate = null;
try {
startDate = g_SimpleDateFormat_I.parse(starttime);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar startTime = Calendar.getInstance();
startTime.clear();
startTime.setTime(startDate);
startTime.add(Calendar.DAY_OF_YEAR, days);
return startTime.getTime();
}
/**
*
* <P>
* 得到起始日期和结束日期之间的天数
* </P>
*
* @param beginStr
* 起始日期
* @param endStr
* 结束日期
* @param format
* 根据 日期参数的格式,传对应的SimpleDateFormat格式
* @return 天数
*/
public static int getDaysInterval(String beginStr, String endStr, SimpleDateFormat format) {
try {
Date beginDate = format.parse(beginStr);
Date endDate = format.parse(endStr);
long millisecond = endDate.getTime() - beginDate.getTime(); // 日期相减得到日期差X(单位:毫秒)
return (int) (millisecond / (1000 * 60 * 60 * 24));
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
/**
* 得到某个时间当天的最后时间 (时分秒为 23:59:59形式)
*/
public static Date getEndDate(Date date) {
if (date != null) {
// 将截止时间设为指定日期的23:59:59
date.setHours(23);
date.setMinutes(59);
date.setSeconds(59);
}
return date;
}
/**
* 得到本月第一天
*
* @return
*/
public static Date getFristDayOfMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
return calendar.getTime();
}
/**
* 得到本月最后一天
*
* @return
*/
public static Date getLastDayOfMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
return calendar.getTime();
}
/**
* 获得本周一的日期
*
* @return
* @throws ParseException
*/
public static Date getMondayOFWeek() throws ParseException {
int mondayPlus = getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(Calendar.DATE, mondayPlus);
Date monday = currentDate.getTime();
String dateStr = getDateTime_I(monday);
StringBuffer sb = new StringBuffer(dateStr);
sb.append(" ").append("00:00:00");
return parseDateStrToDate(sb.toString());
}
/**
* 获得本周星期日的日期
*
* @return
* @throws ParseException
*/
public static Date getCurrentWeekday() throws ParseException {
int mondayPlus = getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(Calendar.DATE, mondayPlus + 6);
Date monday = currentDate.getTime();
String dateStr = getDateTime_I(monday);
StringBuffer sb = new StringBuffer(dateStr);
sb.append(" ").append("00:00:00");
return parseDateStrToDate(sb.toString());
}
/**
* 字符串时间格式转换为 Date
*
* @param date
* 此格式 yyyy-MM-dd HH:mm:ss
* @return
* @throws ParseException
*/
public static Date parseDateStrToDate(String date) throws ParseException {
Date date_time = null;
if (!StringHelper.isEmpty(date)) {
date_time = sdfDateTimeFormat.parse(date);
}
return date_time;
}
/**
* 字符串时间格式转换为 Date
*
* @param date
* 此格式 yyyy-MM-dd
* @return
* @throws ParseException
*/
public static Date parseDateFromStr(String date) throws ParseException {
Date date_time = null;
if (!StringHelper.isEmpty(date)) {
date_time = g_SimpleDateFormat_I.parse(date);
}
return date_time;
}
public static int getMondayPlus() {
Calendar cd = Calendar.getInstance();
// 因为按中国礼拜一作为第一天所以这里减1
int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1;
if (dayOfWeek == 1) {
return 0;
} else if (dayOfWeek == 0) {
return 1 - 7;
} else {
return 1 - dayOfWeek;
}
}
/**
* 得到当天开始时间
*
* @return
* @throws ParseException
*/
public static Date getTodayStartDateTime(Date date) throws ParseException {
String dateStr = getDateTime_I(date);
StringBuffer sb = new StringBuffer(dateStr);
sb.append(" ").append("00:00:00");
return parseDateStrToDate(sb.toString());
}
/**
* 得到当前年份
*
* @return
*/
public static int getCurrentYear() {
Calendar c = Calendar.getInstance();
return c.get(Calendar.YEAR);
}
/**
* 得到当前月份
*
* @return
*/
public static int getMonth() {
Calendar c = Calendar.getInstance();
return c.get(Calendar.MONTH) + 1;
}
/**
* 得到当前日
*
* @return
*/
public static int getDayOfMonth() {
Calendar c = Calendar.getInstance();
return c.get(Calendar.DAY_OF_MONTH);
}
/**
* <p>
* 获得指定的年,int格式
* </p>
* <br>
*
* @param date
* @return
*/
public static int getCustomYear(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.YEAR);
}
/**
* <p>
* 获得指定的月,int格式
* </p>
* <br>
*
* @param date
* @return
*
*/
public static int getCustomMonth(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.MONTH) + 1;
}
/**
* <p>
* 获得指定的日(月份中的),int格式
* </p>
* <br>
*
* @param date
* @return
*/
public static int getCustomDayOfMonth(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.DAY_OF_MONTH);
}
/**
* <p>
* 获得指定的小时(日中的),int格式
* </p>
* <br>
*
* @return
*/
public static int getCustomHour(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.HOUR_OF_DAY);
}
/**
* <p>
* 获得指定的分钟,int格式
* </p>
* <br>
*
* @return
*/
public static int getCustomMinute(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.MINUTE);
}
/**
* <p>
* 获得指定的秒,int格式
* </p>
* <br>
*
* @return
*/
public static int getCustomSecond(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.SECOND);
}
/**
*
* @param beginDate
* @param endDate
* @param f
* 时间差的形式0:秒,1:分种,2:小时,3:天
* @return
*/
public static int getDifferenceNum(Date beginDate, Date endDate, int f) {
int result = 0;
if (beginDate == null || endDate == null) {
return 0;
}
try {
// 日期相减得到日期差X(单位:毫秒)
long millisecond = endDate.getTime() - beginDate.getTime();
/**
* Math.abs((int)(millisecond/1000)); 绝对值 1秒 = 1000毫秒
* millisecond/1000 --> 秒 millisecond/1000*60 - > 分钟
* millisecond/(1000*60*60) -- > 小时 millisecond/(1000*60*60*24) -->
* 天
*/
switch (f) {
case 0: // second
return (int) (millisecond / 1000);
case 1: // minute
return (int) (millisecond / (1000 * 60));
case 2: // hour
return (int) (millisecond / (1000 * 60 * 60));
case 3: // day
return (int) (millisecond / (1000 * 60 * 60 * 24));
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* <p>
* 比较两个日期的大小,精确到秒
* </p>
*
* @param d1
* @param d2
* @date 2016-11-22
* @return 返回一个long类型的整数,若大于0表示第一个日期晚于第二个日期,小于0表示第一个日期早于第二个日期,否则相等
*/
public static long compareEachOther(Date d1, Date d2) {
if (d1 == null || d2 == null)
return -1;
String d1Str = d1.getTime() + "";
String d2Str = d2.getTime() + "";
int l1 = d1Str.length();
int l2 = d2Str.length();
d1Str = d1Str.substring(0, l1 - 3) + "000";
d2Str = d2Str.substring(0, l2 - 3) + "000";
// System.out.println(d1Str + " " + d2Str);
long long1 = Long.parseLong(d1Str);
long long2 = Long.parseLong(d2Str);
return long1 - long2;
}
public static void main(String[] args) throws ParseException {
// //获取当前日期
// System.out.println(getCurrentDate());
// //返回当前时间日期格式(yyyyMMddHHmmss)
// System.out.println(getCurDateTime());
// //返回日期格式(yyyy-MM-dd HH:mm:ss)
// System.out.println(getDateTime(new Date()));
// //返回日期格式(yyyyMMdd)
// System.out.println(getDateTime2(new Date()));
// //获取当前年月格式(yyyyMM)
// System.out.println(getCurrentMonth());
// // 获得本月的几个月。(yyyyMM)
// System.out.println(getBAMonth(-8));
// //获取本月第一天日期(格式如YYYYMMDD),如果当前日为当月1日,则返回上月第一日
// System.out.println(getMonthFirstDay());
// //获取当前时间前几天或后几天的日期
// System.out.println(getAddDays(-1));
// //获取某个月后的日期格式
// System.out.println(getAfterMonth(-1));
System.out.println(getPredate());
// System.out.println(getFristDayOfMonth());
// //
// System.out.println(getCurrentYear());
// //
// System.out.println(getMonth());
// //
// System.out.println(getDayOfMonth());
String prizeInfo = "http://diaosaas-prod.oss-cn-shenzhen.aliyuncs.com/education/155547299256510446.pdf 电子书-初级(上册)-新标日-日语.pdf";
String[] split = prizeInfo.split(" ");
for (int i = 0; i < split.length; i++) {
String string = split[i].toString();
System.out.println(string);
}
int length = prizeInfo.length();
System.out.println(length);
int begin = prizeInfo.indexOf("education");
int last = prizeInfo.length();
System.out.println(prizeInfo.substring(begin, last).replaceAll("education/", ""));
}
/**
* 给时间增加几个小时方法
*
* @param day
* @param hour
* isDate yesDate或者 noDate
* @return
*/
public static Date addDateMinut(Object day, int hour, String isDate) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
if (day == null)
return null;
if (isDate.equals("noDate")) {
date = format.parse(day.toString());
} else {
date = (Date) day;
}
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("front:" + format.format(date)); // 显示输入的日期
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, hour);// 24小时制
date = cal.getTime();
System.out.println("after:" + format.format(date)); // 显示更新后的日期
cal = null;
return date ;
/*format.format(date)*/
}
}
package com.platform.utils.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import com.mysql.fabric.xmlrpc.base.Array;
/**
* 说明:日期处理
* @version
*/
public class DateUtil {
private final static SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
private final static SimpleDateFormat sdfDay = new SimpleDateFormat("yyyy-MM-dd");
private final static SimpleDateFormat sdfDays = new SimpleDateFormat("yyyyMMdd");
private final static SimpleDateFormat sdfTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final static SimpleDateFormat sdfTimes = new SimpleDateFormat("yyyyMMddHHmmss");
/**
* 获取YYYY格式
* @return
*/
public static String getSdfTimes() {
return sdfTimes.format(new Date());
}
/**
* 获取YYYY格式
* @return
*/
public static String getYear() {
return sdfYear.format(new Date());
}
/**
* 获取YYYY-MM-DD格式
* @return
*/
public static String getDay() {
return sdfDay.format(new Date());
}
/**
* 获取YYYYMMDD格式
* @return
*/
public static String getDays(){
return sdfDays.format(new Date());
}
/**
* 获取YYYY-MM-DD HH:mm:ss格式
* @return
*/
public static String getTime() {
return sdfTime.format(new Date());
}
/**
* @Title: compareDate
* @Description: TODO(日期比较,如果s>=e 返回true 否则返回false)
* @param s
* @param e
* @return boolean
* @throws
* @author fh
*/
public static boolean compareDate(String s, String e) {
if(fomatDate(s)==null||fomatDate(e)==null){
return false;
}
return fomatDate(s).getTime() >=fomatDate(e).getTime();
}
/**
* @Title: compareDate
* @Description: TODO(日期比较,如果s>e 返回true 否则返回false)
* @param s
* @param e
* @return boolean
* @throws
* @author fh
*/
public static boolean compareDate_I(String s, String e) {
if(fomatDate(s)==null||fomatDate(e)==null){
return false;
}
return fomatDate(s).getTime() > fomatDate(e).getTime();
}
/**
* 格式化日期
* @return
*/
public static Date fomatDate(String date) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
return fmt.parse(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 校验日期是否合法
* @return
*/
public static boolean isValidDate(String s) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
fmt.parse(s);
return true;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
return false;
}
}
/**
* @param startTime
* @param endTime
* @return
*/
public static int getDiffYear(String startTime,String endTime) {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
try {
//long aa=0;
int years=(int) (((fmt.parse(endTime).getTime()-fmt.parse(startTime).getTime())/ (1000 * 60 * 60 * 24))/365);
return years;
} catch (Exception e) {
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
return 0;
}
}
/**
* <li>功能描述:时间相减得到天数
* @param beginDateStr
* @param endDateStr
* @return
* long
* @author Administrator
*/
public static long getDaySub(String beginDateStr,String endDateStr){
long day=0;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date beginDate = null;
Date endDate = null;
try {
beginDate = format.parse(beginDateStr);
endDate= format.parse(endDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
day=(endDate.getTime()-beginDate.getTime())/(24*60*60*1000);
//System.out.println("相隔的天数="+day);
return day;
}
/**
* 得到n天之后的日期
* @param days
* @return
*/
public static String getAfterDayDate(String days,String format) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdfd = new SimpleDateFormat(format);
String dateStr = sdfd.format(date);
return dateStr;
}
/**
* 得到n天之后是周几
* @param days
* @return
*/
public static String getAfterDayWeek(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("E");
String dateStr = sdf.format(date);
return dateStr;
}
/* public static void main(String[] args) {
System.out.println(getTime());
System.out.println(getAfterDayWeek("3"));
}
*/
/**
* 得到n天之后的YYYY-mm-dd
* @param days
* @return
*/
public static String getAfterDate(String days) {
int daysInt = Integer.parseInt(days);
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, daysInt); // 日期减 如果不够减会将月变动
Date date = canlendar.getTime();
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdfd.format(date);
return dateStr;
}
/**
* 获取当前时间 N 分钟前的时间 字符串格式
* @return
* N 前多少分
* dataType 返回类型 true 为 时间差 ,false 为字符串 yyyy-MM-dd HH:mm:ss
*/
public static Object getCurrentBeforeNMinutesDate(int N,boolean dateType){
// Calendar nowBefore = Calendar.getInstance();
Calendar nowAfter = Calendar.getInstance();
// nowBefore.add(Calendar.MINUTE, N); //;//把日期往后增加SECOND 秒.整数往后推,负数往前移动
nowAfter.add(Calendar.MINUTE, -N);
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// System.out.println( sdf.format(nowBefore.getTimeInMillis()) );
// System.out.println( sdf.format(nowAfter.getTimeInMillis()) );
if(dateType){
return nowAfter.getTimeInMillis();
}else{
return sdf.format(nowAfter.getTimeInMillis());
}
}
/**
* 获取当前时间 N 秒前的时间 字符串格式
* @return
* N 前多少分
* dataType 返回类型 true 为 时间差 ,false 为字符串 yyyy-MM-dd HH:mm:ss
*/
public static Object getCurrentBeforeNSecondDate(int N,boolean dateType){
// Calendar nowBefore = Calendar.getInstance();
Calendar nowAfter = Calendar.getInstance();
// nowBefore.add(Calendar.SECOND, N);
nowAfter.add(Calendar.SECOND, -N); //nowAfter.add(Calendar.SECOND, -30);
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// System.out.println( sdf.format(nowBefore.getTimeInMillis()) );
// System.out.println( sdf.format(nowAfter.getTimeInMillis()) );
if(dateType){
return nowAfter.getTimeInMillis();
}else{
return sdf.format(nowAfter.getTimeInMillis());
}
}
/**
* 获取某时间之前的前N分钟
* N 前多少分 例如30
* dataType 返回类型 true 为 时间差 ,false 为字符串 yyyy-MM-dd HH:mm:ss
* @return
* @throws ParseException
*/
public static Object getBeforeData(String date,int N,boolean dateType) throws ParseException{
Calendar c = new GregorianCalendar();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
c.setTime(simpleDateFormat.parse(date));//设置参数时间
c.add(Calendar.MINUTE,-N);//把日期往后增加SECOND 秒.整数往后推,负数往前移动
Date dates=c.getTime(); //这个时间就是日期往后推一天的结果
System.out.println(date);
System.out.println(simpleDateFormat.format(dates)+" 之后的日期");
long bspeakTime= dates.getTime();
if(dateType){
return dates.getTime();
}else{
return simpleDateFormat.format(dates);
}
}
/**
* 传入的时间与系统当前时间相减,得到天数差,小时差,分钟差
* @param
* @throws ParseException
* wuyulun
*/
public static long minuteDifference(String createTime) throws ParseException {
Date date3 = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date2 = df.parse(createTime);
long diff = date3.getTime() - date2.getTime();// 这样得到的差值是微秒级别
long days = diff / (1000 * 60 * 60 * 24);
long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
return minutes;
}
/**
* 传入的时间与系统当前时间相减,得到天数差,小时差,分钟差
* @param
* @throws ParseException
* wuyulun
*/
public static long hourDifference(String createTime) {
Date date3 = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date2 = null;
try {
date2 = df.parse(createTime);
} catch (ParseException e) {
e.printStackTrace();
}
long diff = date3.getTime() - date2.getTime();// 这样得到的差值是微秒级别
long days = diff / (1000 * 60 * 60 * 24);
long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
return hours;
}
public static void main(String[] args) throws ParseException {
/*System.out.println(getTime());
System.out.println(getAfterDayWeek("3"));*/
// String time = timeplus(5,new Date());
// String time = DateUtil.getTime();
// System.out.println(time);
// String setTime="2018-10-18 1:00:00";
// long hourDifference = DateUtil.hourDifference(setTime);
// System.out.println(hourDifference);
System.out.println(getLastMonths("2017-05",12));
}
/**
*
* @param time 支持 2017-01的时间字符串格式
* @return
*/
public static List<String> getLastMonths(String time,int mouthCount){
//处理月份输入条件
if(time.length()==7){
time=time+"-01 00:00:00";
}else if(time.length()==110){
time=time.substring(0,7)+"-01 00:00:00";
}
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
date= sdf.parse(time);
} catch (ParseException e) {
return null;
}
List<String> lastMonths = new ArrayList<>();
Calendar cal = Calendar.getInstance();
//设置输入条件时间
cal.setTime(date);
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1); //要先+1,才能把本月的算进去
for(int i=0; i<mouthCount; i++){
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)-1); //逐次往前推1个月
lastMonths.add(cal.get(Calendar.YEAR)+ "-" + addZeroForNum(String.valueOf(cal.get(Calendar.MONTH)+1), 2));
}
return lastMonths;
}
public static String addZeroForNum(String str, int strLength) {
int strLen = str.length();
if (strLen < strLength) {
while (strLen < strLength) {
StringBuffer sb = new StringBuffer();
sb.append("0").append(str);// 左补0
// sb.append(str).append("0");//右补0
str = sb.toString();
strLen = str.length();
}
}
return str;
}
/**
* 通过时间秒毫秒数判断两个时间的间隔
* @param date1 时间小
* @param date2 时间大
* @return
*/
public static int differentDaysByMillisecond(Date date1,Date date2)
{
int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
return days;
}
/**
*
* @param time yyyy-MM-dd
* @return String yyyy
*/
public static String getYearByStringTime(String time) {
try {
Date date = sdfDay.parse(time);
String year = sdfYear.format(date);
return year;
}catch (ParseException e){
e.getErrorOffset();
}
return null;
}
/**
*
* @Function: getDays
* @Description: (获取两个日期之间的所有日期)
* @param:
* @return:
* @since JDK 1.8
* @throws
*/
public static List<String> getDays(String startTime, String endTime) {
// 返回的日期集合
List<String> days = new ArrayList<String>();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date start = dateFormat.parse(startTime);
Date end = dateFormat.parse(endTime);
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
while (tempStart.before(tempEnd)) {
days.add(dateFormat.format(tempStart.getTime()));
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return days;
}
/**
* 获取过去或者未来 任意天内的日期数组
* @param intervals intervals天内
* @return 日期数组
*/
public static ArrayList<String> test(int intervals ) {
ArrayList<String> pastDaysList = new ArrayList<>();
ArrayList<String> fetureDaysList = new ArrayList<>();
for (int i = 0; i <intervals; i++) {
pastDaysList.add(getPastDate(i));
fetureDaysList.add(getFetureDate(i));
}
return pastDaysList;
}
/**
* 获取过去第几天的日期
*
* @param past
* @return
*/
public static String getPastDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
Date today = calendar.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String result = format.format(today);
return result;
}
/**
* 获取未来 第 past 天的日期
* @param past
* @return
*/
public static String getFetureDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
Date today = calendar.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String result = format.format(today);
return result;
}
}
package com.platform.utils.util;
import java.io.File;
/**
* java删除所有文件和文件夹
* @version
*/
public class DelAllFile {
public static void main(String args[]) {
delFolder("e:/e/a"); //只删除e下面a及a下面所有文件和文件夹,e不会被删掉
//delFolder("D:/WEBSerser/apache-tomcat-8.0.15/me-webapps/UIMYSQL/WEB-INF/classes/../../admin00/ftl/code");
//delFolder("D:\\WEBSerser\\apache-tomcat-8.0.15\\me-webapps\\UIMYSQL\\admin00\\ftl\\code");
//delFolder("D:/WEBSerser/apache-tomcat-8.0.15/me-webapps/UIMYSQL/WEB-INF/classes/../../admin00/ftl/code");
System.out.println("deleted");
}
/**
* @param folderPath 文件路径 (只删除此路径的最末路径下所有文件和文件夹)
*/
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath); // 删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
File myFilePath = new File(filePath);
myFilePath.delete(); // 删除空文件夹
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除指定文件夹下所有文件
* @param path 文件夹完整绝对路径
*/
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]); // 先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]); // 再删除空文件夹
flag = true;
}
}
return flag;
}
}
package com.platform.utils.util;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.github.binarywang.java.emoji.EmojiConverter;
import com.vdurmont.emoji.EmojiParser;
import com.vdurmont.emoji.EmojiParser.EmojiTransformer;
import com.vdurmont.emoji.EmojiParser.UnicodeCandidate;
public class Emoji extends EmojiParser {
/**
* 获取非表情字符串
*
* @param input
* @return
*/
public static String getNonEmojiString(String input) {
int prev = 0;
StringBuilder sb = new StringBuilder();
List<UnicodeCandidate> replacements = getUnicodeCandidates(input);
for (UnicodeCandidate candidate : replacements) {
sb.append(input.substring(prev, candidate.getEmojiStartIndex()));
prev = candidate.getFitzpatrickEndIndex();
}
return sb.append(input.substring(prev)).toString();
}
/**
* 获取表情字符串
*
* @param input
* @return
*/
public static String getEmojiUnicodeString(String input) {
EmojiTransformer transformer = new EmojiTransformer() {
public String transform(UnicodeCandidate unicodeCandidate) {
return unicodeCandidate.getEmoji().getHtmlHexadecimal();
}
};
StringBuilder sb = new StringBuilder();
List<UnicodeCandidate> replacements = getUnicodeCandidates(input);
for (UnicodeCandidate candidate : replacements) {
sb.append(transformer.transform(candidate));
}
return parseToUnicode(sb.toString());
}
public static String getUnicode(String source) {
String returnUniCode = null;
String uniCodeTemp = null;
for (int i = 0; i < source.length(); i++) {
uniCodeTemp = "\\u" + Integer.toHexString((int) source.charAt(i));
returnUniCode = returnUniCode == null ? uniCodeTemp : returnUniCode + uniCodeTemp;
}
return returnUniCode;
}
/**
* 判断是否包含emoji表情
*
* @return 过滤后的结果
*/
public static boolean checkEmoji(String source) {
if (StringUtils.isNotBlank(source)) {
return source.matches("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]");
} else {
return false;
}
}
/**
* emoji表情替换
*
* @param source 原字符串
* @param slipStr emoji表情替换成的字符串
* @return 过滤后的字符串
*/
public static String filterEmoji(String source,String slipStr) {
if(StringUtils.isNotBlank(source)){
return source.replaceAll("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]", slipStr);
}else{
return source;
}
}
public static void main(String[] args) throws Exception {
String content2 = "傻逼\ud83d\ude0f\ud83d\ude0fVincent\ud83d\udc36 Vincent";
String string ="Vincent\ud83d\udc36";
String bString = unicodeToUtf8(string);
System.out.println(bString);
//String string2 = emojiConverterUnicodeStr(content2);
String string3 = emojiConverterToAlias(content2);
String emojiConverterUnicodeStr = emojiConverterUnicodeStr(string3);
System.out.println(string3);
System.out.println(emojiConverterUnicodeStr);
}
/**
* unicode 转换成 utf-8
*
* @author fanhui 2007-3-15
* @param theString
* @return
*/
public static String unicodeToUtf8(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't')
aChar = '\t';
else if (aChar == 'r')
aChar = '\r';
else if (aChar == 'n')
aChar = '\n';
else if (aChar == 'f')
aChar = '\f';
outBuffer.append(aChar);
}
} else
outBuffer.append(aChar);
}
return outBuffer.toString();
}
private static EmojiConverter emojiConverter = EmojiConverter.getInstance();
/**
* 将emojiStr转为 带有表情的字符
* @param emojiStr
* @return
*/
public static String emojiConverterUnicodeStr(String emojiStr){
String result = emojiConverter.toUnicode(emojiStr);
return result;
}
/**
* 带有表情的字符串转换为编码
* @param str
* @return
*/
public static String emojiConverterToAlias(String str){
String result=emojiConverter.toAlias(str);
return result;
}
}
package com.platform.utils.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
*   
*
* @Title: FastJsonUtil.java
* @Package com.jarvis.base.util
* @Description:fastjson工具类
* @author Jack 
* @date 2017年9月2日 下午4:16:27
* @version V1.0  
*/
public class FastJsonUtil {
private static final SerializeConfig config;
static {
config = new SerializeConfig();
config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式
}
private static final SerializerFeature[] features = { SerializerFeature.WriteMapNullValue, // 输出空置字段
SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null
SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null
SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null
SerializerFeature.WriteNullStringAsEmpty, // 字符类型字段如果为null,输出为"",而不是null
SerializerFeature.PrettyFormat //是否需要格式化输出Json数据
};
/**
* Author:Jack Time:2017年9月2日下午4:24:14
*
* @param object
* @return Return:String Description:将对象转成成Json对象
*/
public static String toJSONString(Object object) {
return JSON.toJSONString(object, config, features);
}
/**
* Author:Jack Time:2017年9月2日下午4:27:25
*
* @param object
* @return Return:String Description:使用和json-lib兼容的日期输出格式
*/
public static String toJSONNoFeatures(Object object) {
return JSON.toJSONString(object, config);
}
/**
* Author:Jack Time:2017年9月2日下午4:24:54
*
* @param jsonStr
* @return Return:Object Description:将Json数据转换成JSONObject
*/
public static JSONObject toJsonObj(String jsonStr) {
return (JSONObject) JSON.parse(jsonStr);
}
/**
* Author:Jack Time:2017年9月2日下午4:25:20
*
* @param jsonStr
* @param clazz
* @return Return:T Description:将Json数据转换成Object
*/
public static <T> T toBean(String jsonStr, Class<T> clazz) {
return JSON.parseObject(jsonStr, clazz);
}
/**
* Author:Jack Time:2017年9月2日下午4:25:34
*
* @param jsonStr
* @return Return:Object[] Description:将Json数据转换为数组
*/
public static <T> Object[] toArray(String jsonStr) {
return toArray(jsonStr, null);
}
/**
* Author:Jack Time:2017年9月2日下午4:25:57
*
* @param jsonStr
* @param clazz
* @return Return:Object[] Description:将Json数据转换为数组
*/
public static <T> Object[] toArray(String jsonStr, Class<T> clazz) {
return JSON.parseArray(jsonStr, clazz).toArray();
}
/**
* Author:Jack Time:2017年9月2日下午4:26:08
*
* @param jsonStr
* @param clazz
* @return Return:List<T> Description:将Json数据转换为List
*/
public static <T> List<T> toList(String jsonStr, Class<T> clazz) {
return JSON.parseArray(jsonStr, clazz);
}
/**
* 将javabean转化为序列化的JSONObject对象
*
* @param keyvalue
* @return
*/
public static JSONObject beanToJsonObj(Object bean) {
String jsonStr = JSON.toJSONString(bean);
JSONObject objectJson = (JSONObject) JSON.parse(jsonStr);
return objectJson;
}
/**
* json字符串转化为map
*
* @param s
* @return
*/
public static Map<?, ?> stringToCollect(String jsonStr) {
Map<?, ?> map = JSONObject.parseObject(jsonStr);
return map;
}
/**
* 将map转化为string
*
* @param m
* @return
*/
public static String collectToString(Map<?, ?> map) {
String jsonStr = JSONObject.toJSONString(map);
return jsonStr;
}
/**
* Author:Jack Time:2017年9月2日下午4:19:00
*
* @param t
* @param file
* @throws IOException
* Return:void Description:将对象的Json数据写入文件。
*/
public static <T> void writeJsonToFile(T t, File file) throws IOException {
String jsonStr = JSONObject.toJSONString(t, SerializerFeature.PrettyFormat);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(jsonStr);
bw.close();
}
/**
* Author:Jack Time:2017年9月2日下午4:19:12
*
* @param t
* @param filename
* @throws IOException
* Return:void Description:将对象的Json数据写入文件。
*/
public static <T> void writeJsonToFile(T t, String filename) throws IOException {
writeJsonToFile(t, new File(filename));
}
/**
* Author:Jack Time:2017年9月2日下午4:22:07
*
* @param cls
* @param file
* @return
* @throws IOException
* Return:T Description:将文件中的Json数据转换成Object对象
*/
public static <T> T readJsonFromFile(Class<T> cls, File file) throws IOException {
StringBuilder strBuilder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while ((line = br.readLine()) != null) {
strBuilder.append(line);
}
br.close();
return JSONObject.parseObject(strBuilder.toString(), cls);
}
/**
* Author:Jack Time:2017年9月2日下午4:22:30
*
* @param cls
* @param filename
* @return
* @throws IOException
* Return:T Description:将文件中的Json数据转换成Object对象
*/
public static <T> T readJsonFromFile(Class<T> cls, String filename) throws IOException {
return readJsonFromFile(cls, new File(filename));
}
/**
* Author:Jack Time:2017年9月2日下午4:23:06
*
* @param typeReference
* @param file
* @return
* @throws IOException
* Return:T Description:从文件中读取出Json对象
*/
public static <T> T readJsonFromFile(TypeReference<T> typeReference, File file) throws IOException {
StringBuilder strBuilder = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while ((line = br.readLine()) != null) {
strBuilder.append(line);
}
br.close();
return JSONObject.parseObject(strBuilder.toString(), typeReference);
}
/**
* Author:Jack Time:2017年9月2日下午4:23:11
*
* @param typeReference
* @param filename
* @return
* @throws IOException
* Return:T Description:从文件中读取出Json对象
*/
public static <T> T readJsonFromFile(TypeReference<T> typeReference, String filename) throws IOException {
return readJsonFromFile(typeReference, new File(filename));
}
}
\ No newline at end of file
package com.platform.utils.util;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import com.google.common.io.ByteStreams;
/**
* 下载文件
* @version
*/
public class FileDownload {
/**
* @param response
* @param filePath //文件完整路径(包括文件名和扩展名)
* @param fileName //下载后看到的文件名
* @return 文件名
*/
public static void fileDownload(final HttpServletResponse response, String filePath, String fileName) throws Exception{
byte[] data = FileUtil.toByteArray2(filePath);
fileName = URLEncoder.encode(fileName, "UTF-8");
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(data);
outputStream.flush();
outputStream.close();
response.flushBuffer();
}
/**
* @param response
* @param url http://aidiyuns......jpg
* @param fileName //下载后看到的文件名
* @return 文件名
*/
public static void fileDownload2(HttpServletResponse response, String url, String fileName) throws Exception{
// 获取文件后缀
String prefix=url.substring(url.lastIndexOf("."));
fileName = fileName+prefix;
InputStream inputStream = FileDownload.getImageStream(url);
byte[] fileByte = ByteStreams.toByteArray(inputStream);
fileName = URLEncoder.encode(fileName, "UTF-8");
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.addHeader("Content-Length", "" + fileByte.length);
response.setContentType("application/octet-stream;charset=UTF-8");
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(fileByte);
outputStream.flush();
outputStream.close();
response.flushBuffer();
}
/**
* 通过URL获取网络图片 https://blog.csdn.net/x541211190/article/details/80784582
* 获取网络图片流
*
* @param url 传入的URL必须是以http://开头的,因为我们使用了HttpURLConnection,示例:
* @return
*/
public static InputStream getImageStream(String url) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
return inputStream;
}
} catch (IOException e) {
System.out.println("获取网络图片出现异常,图片路径为:" + url);
e.printStackTrace();
}
return null;
}
}
package com.platform.utils.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
/**
* 上传文件
* @version
*/
public class FileUpload {
/**上传文件
* @param file //文件对象
* @param filePath //上传路径
* @param fileName //文件名
* @return 文件名
*/
public static String fileUp(MultipartFile file, String filePath, String fileName){
String extName = ""; // 扩展名格式:
try {
if (file.getOriginalFilename().lastIndexOf(".") >= 0){
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}
copyFile(file.getInputStream(), filePath, fileName+extName).replaceAll("-", "");
} catch (IOException e) {
System.out.println(e);
}
return fileName+extName;
}
/**
* 写文件到当前目录的upload目录中
* @param in
* @param fileName
* @throws IOException
*/
private static String copyFile(InputStream in, String dir, String realName)
throws IOException {
File file = mkdirsmy(dir,realName);
FileUtils.copyInputStreamToFile(in, file);
return realName;
}
/**判断路径是否存在,否:创建此路径
* @param dir 文件路径
* @param realName 文件名
* @throws IOException
*/
public static File mkdirsmy(String dir, String realName) throws IOException{
File file = new File(dir, realName);
if (!file.exists()) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
}
return file;
}
/**下载网络图片上传到服务器上
* @param httpUrl 图片网络地址
* @param filePath 图片保存路径
* @param myFileName 图片文件名(null时用网络图片原名)
* @return 返回图片名称
*/
public static String getHtmlPicture(String httpUrl, String filePath , String myFileName) {
URL url; //定义URL对象url
BufferedInputStream in; //定义输入字节缓冲流对象in
FileOutputStream file; //定义文件输出流对象file
try {
String fileName = null == myFileName?httpUrl.substring(httpUrl.lastIndexOf("/")).replace("/", ""):myFileName; //图片文件名(null时用网络图片原名)
url = new URL(httpUrl); //初始化url对象
in = new BufferedInputStream(url.openStream()); //初始化in对象,也就是获得url字节流
//file = new FileOutputStream(new File(filePath +"\\"+ fileName));
file = new FileOutputStream(mkdirsmy(filePath,fileName));
int t;
while ((t = in.read()) != -1) {
file.write(t);
}
file.close();
in.close();
return fileName;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.platform.utils.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
/** 文件处理
* 创建时间:2014年12月23日
*/
public class FileUtil {
/**获取文件大小 返回 KB 保留3位小数 没有文件时返回0
* @param filepath 文件完整路径,包括文件名
* @return
*/
public static Double getFilesize(String filepath){
File backupath = new File(filepath);
return Double.valueOf(backupath.length())/1000.000;
}
/**
* 创建目录
* @param destDirName目标目录名
* @return
*/
public static Boolean createDir(String destDirName) {
File dir = new File(destDirName);
if(!dir.getParentFile().exists()){ //判断有没有父路径,就是判断文件整个路径是否存在
return dir.getParentFile().mkdirs(); //不存在就全部创建
}
return false;
}
/**
* 删除文件
* @param filePathAndName
* String 文件路径及名称 如c:/fqf.txt
* @param fileContent
* String
* @return boolean
*/
public static void delFile(String filePathAndName) {
try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myDelFile = new File(filePath);
myDelFile.delete();
} catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();
}
}
/**
* 读取到字节数组0
* @param filePath //路径
* @throws IOException
*/
public static byte[] getContent(String filePath) throws IOException {
File file = new File(filePath);
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
System.out.println("file too big...");
return null;
}
FileInputStream fi = new FileInputStream(file);
byte[] buffer = new byte[(int) fileSize];
int offset = 0;
int numRead = 0;
while (offset < buffer.length
&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
}
// 确保所有数据均被读取
if (offset != buffer.length) {
throw new IOException("Could not completely read file " + file.getName());
}
fi.close();
return buffer;
}
/**
* 读取到字节数组1
*
* @param filePath
* @return
* @throws IOException
*/
public static byte[] toByteArray(String filePath) throws IOException {
File f = new File(filePath);
if (!f.exists()) {
throw new FileNotFoundException(filePath);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_size))) {
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
}
/**
* 读取到字节数组2
*
* @param filePath
* @return
* @throws IOException
*/
public static byte[] toByteArray2(String filePath) throws IOException {
File f = new File(filePath);
if (!f.exists()) {
throw new FileNotFoundException(filePath);
}
FileChannel channel = null;
FileInputStream fs = null;
try {
fs = new FileInputStream(f);
channel = fs.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
while ((channel.read(byteBuffer)) > 0) {
// do nothing
// System.out.println("reading");
}
return byteBuffer.array();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Mapped File way MappedByteBuffer 可以在处理大文件时,提升性能
*
* @param filename
* @return
* @throws IOException
*/
public static byte[] toByteArray3(String filePath) throws IOException {
FileChannel fc = null;
RandomAccessFile rf = null;
try {
rf = new RandomAccessFile(filePath, "r");
fc = rf.getChannel();
MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0,
fc.size()).load();
//System.out.println(byteBuffer.isLoaded());
byte[] result = new byte[(int) fc.size()];
if (byteBuffer.remaining() > 0) {
// System.out.println("remain");
byteBuffer.get(result, 0, byteBuffer.remaining());
}
return result;
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
rf.close();
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
\ No newline at end of file
package com.platform.utils.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**java压缩成zip
* 创建时间:2015年1月14日
*/
public class FileZip {
/**
* @param inputFileName 你要压缩的文件夹(整个完整路径)
* @param zipFileName 压缩后的文件(整个完整路径)
* @throws Exception
*/
public static Boolean zip(String inputFileName, String zipFileName) throws Exception {
zip(zipFileName, new File(inputFileName));
return true;
}
private static void zip(String zipFileName, File inputFile) throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
zip(out, inputFile, "");
out.flush();
out.close();
}
private static void zip(ZipOutputStream out, File f, String base) throws Exception {
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
} else {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
//System.out.println(base);
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
}
}
public static void main(String [] temp){
try {
zip("E:\\ftl","E:\\test.zip");//你要压缩的文件夹 和 压缩后的文件
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
//=====================文件压缩=========================
/*//把文件压缩成zip
File zipFile = new File("E:/demo.zip");
//定义输入文件流
InputStream input = new FileInputStream(file);
//定义压缩输出流
ZipOutputStream zipOut = null;
//实例化压缩输出流,并制定压缩文件的输出路径 就是E盘下,名字叫 demo.zip
zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
zipOut.putNextEntry(new ZipEntry(file.getName()));
//设置注释
zipOut.setComment("www.demo.com");
int temp = 0;
while((temp = input.read()) != -1) {
zipOut.write(temp);
}
input.close();
zipOut.close();*/
//==============================================
package com.platform.utils.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* Freemarker 模版引擎类
* 创建时间:2015年2月8日
* @version
*/
public class Freemarker {
/**
* 打印到控制台(测试用)
* @param ftlName
*/
public static void print(String ftlName, Map<String,Object> root, String ftlPath) throws Exception{
try {
Template temp = getTemplate(ftlName, ftlPath); //通过Template可以将模板文件输出到相应的流
temp.process(root, new PrintWriter(System.out));
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 输出到输出到文件
* @param ftlName ftl文件名
* @param root 传入的map
* @param outFile 输出后的文件全部路径
* @param filePath 输出前的文件上部路径
*/
public static void printFile(String ftlName, Map<String,Object> root, String outFile, String filePath, String ftlPath) throws Exception{
try {
File file = new File(PathUtil.getClasspath() + filePath + outFile);
if(!file.getParentFile().exists()){ //判断有没有父路径,就是判断文件整个路径是否存在
file.getParentFile().mkdirs(); //不存在就全部创建
}
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
Template template = getTemplate(ftlName, ftlPath);
template.process(root, out); //模版输出
out.flush();
out.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 通过文件名加载模版
* @param ftlName
*/
public static Template getTemplate(String ftlName, String ftlPath) throws Exception{
try {
Configuration cfg = new Configuration(); //通过Freemaker的Configuration读取相应的ftl
cfg.setEncoding(Locale.CHINA, "utf-8");
cfg.setDirectoryForTemplateLoading(new File(PathUtil.getClassResources()+"/ftl/"+ftlPath)); //设定去哪里读取相应的ftl模板文件
Template temp = cfg.getTemplate(ftlName); //在模板文件目录中找到名称为name的文件
return temp;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.platform.utils.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @version
*/
public class GetWeb {
/**
* 获取当前网页的code
*
* @param httpUrl
* 网页地址
* @return
* @throws IOException
*/
public static String getHtmlCode(String httpUrl) throws IOException {
String content = ""; // 定义字符串content
URL url = new URL(httpUrl); // 生成传入的URL的对象
BufferedReader reader = new BufferedReader(new InputStreamReader(
url.openStream(), "utf-8"));// 获得当前url的字节流(缓冲)
String input;
while ((input = reader.readLine()) != null) { // 当前行存在数据时
content += input; // 将读取数据赋给content
}
reader.close(); // 关闭缓冲区
return content;
}
/**
* 把网页中的所有图片的完整路径放到list里面
*
* @param wwwurl
* 要爬的网页连接
* @throws IOException
*/
public static List<String> getImagePathList(String httpUrl)
throws IOException {
// 通过扩展名匹配网页图片的正则表达式
// String searchImgReg =
// "(?x)(src|SRC|background|BACKGROUND)=('|\")/?(([\\w-]+/)*([\\w-]+\\.(jpg|JPG|png|PNG|gif|GIF)))('|\")";
// String searchImgReg2 =
// "(?x)(src|SRC|background|BACKGROUND)=('|\")(http://([\\w-]+\\.)+[\\w-]+(:[0-9]+)*(/[\\w-]+)*(/[\\w-]+\\.(jpg|JPG|png|PNG|gif|GIF)))('|\")";
// 通过img标签匹配网页图片的正则表达式
String searchImgReg = "<(img|IMG)\\b[^>]*\\b(src|SRC|src2|SRC2)\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic)\\b)[^>]*>";
List<String> imgList = new ArrayList<String>(); // 存放图片的list
String content = null;
content = getHtmlCode(httpUrl); // 获得content
Pattern pattern = Pattern.compile(searchImgReg); // 讲编译的正则表达式对象赋给pattern
Matcher matcher = pattern.matcher(content); // 对字符串content执行正则表达式
while (matcher.find()) {
String quote = matcher.group(3);
String imgsrc = (quote == null || quote.trim().length() == 0) ? matcher.group(4).split("\\s+")[0] : matcher.group(4);
if (!imgsrc.startsWith("http://") && !imgsrc.startsWith("https://")) { // 检验地址是否http://
String[] httpUrlarr = httpUrl.split("/");
String wwwhost = httpUrlarr[0] + "//" + httpUrlarr[2]; //获取域名完整地址 http://www.xxx.com
if(!isNetFileAvailable(wwwhost + "/" + imgsrc)){
for(int i=3;i<httpUrlarr.length;i++){
wwwhost = wwwhost + "/" + httpUrlarr[i];
if(isNetFileAvailable(wwwhost + "/" + imgsrc)){
imgsrc = wwwhost + "/" + imgsrc;
break;
}
}
}else{
imgsrc = wwwhost + "/" + imgsrc;
}
}
imgList.add(imgsrc);
}
return imgList;
}
/**
* 获取网页的标题
*
* @param httpUrl
* 要爬的网页连接
* @return
*/
public static String getTilte(String httpUrl) {
String searchTitle = "(<title>|<TITLE>)(.*?)(</title>|</TITLE>)"; // 获取网页的标题的正则表达式
Pattern pattern = Pattern.compile(searchTitle); // 获得content
try {
Matcher matcher = pattern.matcher(getHtmlCode(httpUrl));
while (matcher.find()) {
return matcher.group(2);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 检测网络资源是否存在 
*
* @param strUrl
* @return
*/
public static boolean isNetFileAvailable(String strUrl) {
InputStream netFileInputStream = null;
try {
URL url = new URL(strUrl);
URLConnection urlConn = url.openConnection();
netFileInputStream = urlConn.getInputStream();
if (null != netFileInputStream) {
return true;
} else {
return false;
}
} catch (IOException e) {
return false;
} finally {
try {
if (netFileInputStream != null)
netFileInputStream.close();
} catch (IOException e) {
}
}
}
}
// 创建人:FH Q 31 359 679 0
\ No newline at end of file
package com.platform.utils.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* 用于模拟HTTP请求中GET/POST方式
*
*/
public class HttpUtils {
/**
* 发送GET请求
*
* @param url
* 目的地址
* @param parameters
* 请求参数,Map类型。
* @return 远程响应结果
*/
public static String sendGet(String url, Map<String, String> parameters) {
String result="";
BufferedReader in = null;// 读取响应输入流
StringBuffer sb = new StringBuffer();// 存储参数
String params = "";// 编码之后的参数
String full_url = url;
try {
if(parameters!=null){
// 编码请求参数
if(parameters.size()==1){
for(String name:parameters.keySet()){
sb.append(name).append("=").append(
java.net.URLEncoder.encode(parameters.get(name),
"UTF-8"));
}
params=sb.toString();
}else{
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(
java.net.URLEncoder.encode(parameters.get(name),
"UTF-8")).append("&");
}
String temp_params = sb.toString();
params = temp_params.substring(0, temp_params.length() - 1);
}
full_url = url + "?" + params;
}
// System.out.println(full_url);
// 创建URL对象
URL connURL = new URL(full_url);
// 打开URL连接
HttpURLConnection httpConn = (HttpURLConnection) connURL
.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 建立实际的连接
httpConn.connect();
// 响应头部获取
// Map<String, List<String>> headers = httpConn.getHeaderFields();
// 遍历所有的响应头字段
// for (String key : headers.keySet()) {
// System.out.println(key + "\t:\t" + headers.get(key));
// }
// 定义BufferedReader输入流来读取URL的响应,并设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn
.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result ;
}
/**
* 发送POST请求
*
* @param url
* 目的地址
* @param parameters
* 请求参数,Map类型。
* @return 远程响应结果
*/
public static String sendPost(String url, Map<String, String> parameters) {
String result = "";// 返回的结果
BufferedReader in = null;// 读取响应输入流
PrintWriter out = null;
StringBuffer sb = new StringBuffer();// 处理请求参数
String params = "";// 编码之后的参数
try {
// 编码请求参数
if (parameters.size() == 1) {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(
java.net.URLEncoder.encode(parameters.get(name),
"UTF-8"));
}
params = sb.toString();
} else {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(
java.net.URLEncoder.encode(parameters.get(name),
"UTF-8")).append("&");
}
String temp_params = sb.toString();
params = temp_params.substring(0, temp_params.length() - 1);
}
// 创建URL对象
URL connURL = new URL(url);
// 打开URL连接
HttpURLConnection httpConn = (HttpURLConnection) connURL
.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 设置POST方式
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
// 获取HttpURLConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream());
// 发送请求参数
out.write(params);
// System.out.println(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应,设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn
.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
*Author:Jack
*Time:2017年9月5日下午2:20:26
*@param url
*@param parameters
*@return
*Return:String
*Description:发送Post请求,并且发送的是Json格式的数据。
*/
public static String sendPostJson(String url, Map<String, String> parameters) {
String result = "";// 返回的结果
BufferedReader in = null;// 读取响应输入流
PrintWriter out = null;
String params = "";// 编码之后的参数
try {
if(parameters!=null && parameters.size()>0){
params = FastJsonUtil.toJSONString(parameters);
}
// 创建URL对象
URL connURL = new URL(url);
// 打开URL连接
HttpURLConnection httpConn = (HttpURLConnection) connURL
.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 设置POST方式
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
// 获取HttpURLConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream());
// 发送请求参数
out.write(params);
// System.out.println(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应,设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn
.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* http post 提交
* @param url
* @param params
*/
/**
* 模拟请求
*
* @param url 资源地址
* @param map 参数列表
* @param encoding 编码
* @return
* @throws ParseException
* @throws IOException
*/
public static String sendPost(String url, Map<String,String> map,String encoding) throws IOException{
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
//装填参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
if(map!=null){
for (Entry<String, String> entry : map.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//设置参数到请求对象中
httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
System.out.println("请求地址:"+url);
System.out.println("请求参数:"+nvps.toString());
//设置header信息
//指定报文头【Content-type】、【User-Agent】
httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}
/**
* 发送POST请求 ,postman中raw 方式
*
* @param url
* 目的地址
* @param parameters
* 请求参数,Map类型。
* @return 远程响应结果
*
* 例如:
* 获取小程序新增或活跃用户的画像分布数据。
String url = "https://api.weixin.qq.com/datacube/getweanalysisappiduserportrait?access_token="+ token;
String parameters = "{\"begin_date\":\"2019-01-02\",\"end_date\":\"2019-01-02\"}";
*/
public static String sendPost(String url,String parameters) {
String result = "";// 返回的结果
BufferedReader in = null;// 读取响应输入流
PrintWriter out = null;
StringBuffer sb = new StringBuffer();// 处理请求参数
String params = "";// 编码之后的参数
try {
// 编码请求参数
// params = java.net.URLEncoder.encode(parameters, "UTF-8");
params = parameters;
// 创建URL对象
URL connURL = new URL(url);
// 打开URL连接
HttpURLConnection httpConn = (HttpURLConnection) connURL
.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Content-Type", "application/json;");
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 设置POST方式
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
// 获取HttpURLConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream());
// 发送请求参数
out.write(params);
// System.out.println(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应,设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn
.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* 主函数,测试请求
*
* @param args
*/
// public static void main(String[] args) {
// Map<String, String> parameters = new HashMap<String, String>();
// parameters.put("name", "sarin");
// String result =sendGet("http://www.baidu.com", parameters);
// System.out.println(result);
// }
/**
* 获取网络图片流
*
* @param url
* @return
* 传入的URL必须是以http://开头的,因为我们使用了HttpURLConnection,示例:
*/
public static InputStream getImageStream(String url) {
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
return inputStream;
}
} catch (IOException e) {
System.out.println("获取网络图片出现异常,图片路径为:" + url);
e.printStackTrace();
}
return null;
}
}
\ No newline at end of file
package com.platform.utils.util;
public class ImageUploadResult {
public String state;
public String url;
public String title;
public String original;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOriginal() {
return original;
}
public void setOriginal(String original) {
this.original = original;
}
}
package com.platform.utils.util;
/**
* 说明:
* @version
*/
public class LatLonUtil {
private static final double PI = 3.14159265; // 圆周率
private static final double EARTH_RADIUS = 6378137; // 地球半径
private static final double RAD = Math.PI / 180.0; // 一百八十度角
/**
* @param raidus
* 单位米 return minLat
* 最小经度 minLng
* 最小纬度 maxLat
* 最大经度 maxLng
* 最大纬度 minLat
*/
public static double[] getAround(double lat, double lon, int raidus) {
Double latitude = lat;// 传值给经度
Double longitude = lon;// 传值给纬度
Double degree = (24901 * 1609) / 360.0; // 获取每度
double raidusMile = raidus;
Double dpmLat = 1 / degree;
Double radiusLat = dpmLat * raidusMile;
// 获取最小纬度
Double minLat = latitude - radiusLat;
// 获取最大纬度
Double maxLat = latitude + radiusLat;
Double mpdLng = degree * Math.cos(latitude * (PI / 180));
Double dpmLng = 1 / mpdLng;
Double radiusLng = dpmLng * raidusMile;
//获取最小经度
Double minLng = longitude - radiusLng;
// 获取最大经度
Double maxLng = longitude + radiusLng;
System.out.println("jingdu" + minLat + "weidu" + minLng + "zuidajingdu"
+ maxLat + "zuidaweidu" + maxLng);
return new double[] { minLat, minLng, maxLat, maxLng };
}
//测试方法
public static void main(String [] src){
getAround(36.68027, 117.12744, 1000);
}
}
\ No newline at end of file
package com.platform.utils.util;
/**
* 说明:日志处理
* @version
*/
public class Logger {
private org.apache.log4j.Logger logger;
/**
* 构造方法,初始化Log4j的日志对象
*/
private Logger(org.apache.log4j.Logger log4jLogger) {
logger = log4jLogger;
}
/**
* 获取构造器,根据类初始化Logger对象
*
* @param Class
* Class对象
* @return Logger对象
*/
public static Logger getLogger(Class classObject) {
return new Logger(org.apache.log4j.Logger.getLogger(classObject));
}
/**
* 获取构造器,根据类名初始化Logger对象
*
* @param String
* 类名字符串
* @return Logger对象
*/
public static Logger getLogger(String loggerName) {
return new Logger(org.apache.log4j.Logger.getLogger(loggerName));
}
public void debug(Object object) {
logger.debug(object);
}
public void debug(Object object, Throwable e) {
logger.debug(object, e);
}
public void info(Object object) {
logger.info(object);
}
public void info(Object object, Throwable e) {
logger.info(object, e);
}
public void warn(Object object) {
logger.warn(object);
}
public void warn(Object object, Throwable e) {
logger.warn(object, e);
}
public void error(Object object) {
logger.error(object);
}
public void error(Object object, Throwable e) {
logger.error(object, e);
}
public void fatal(Object object) {
logger.fatal(object);
}
public String getName() {
return logger.getName();
}
public org.apache.log4j.Logger getLog4jLogger() {
return logger;
}
public boolean equals(Logger newLogger) {
return logger.equals(newLogger.getLog4jLogger());
}
}
\ No newline at end of file
package com.platform.utils.util;
import java.security.MessageDigest;
/**
* 说明:MD5处理
* 修改时间:2014年9月20日
* @version
*/
public class MD5 {
public static String md5(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
str = buf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public static void main(String[] args) {
System.out.println(md5("31119@qq.com"+"123456"));
System.out.println(md5("mj1"));
}
}
package com.platform.utils.util;
import java.util.HashMap;
import java.util.Map;
/**
* 说明:经纬度处理
* 修改时间:2014年9月20日
* @version
*/
public class MapDistance {
private static double EARTH_RADIUS = 6378.137;
private static double rad(double d) {
return d * Math.PI / 180.0;
}
/**
* 根据两个位置的经纬度,来计算两地的距离(单位为KM)
* 参数为String类型
* @param lat1 用户经度
* @param lng1 用户纬度
* @param lat2 商家经度
* @param lng2 商家纬度
* @return
*/
public static String getDistance(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {
Double lat1 = Double.parseDouble(lat1Str);
Double lng1 = Double.parseDouble(lng1Str);
Double lat2 = Double.parseDouble(lat2Str);
Double lng2 = Double.parseDouble(lng2Str);
double patm = 2;
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double difference = radLat1 - radLat2;
double mdifference = rad(lng1) - rad(lng2);
double distance = patm * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / patm), patm)
+ Math.cos(radLat1) * Math.cos(radLat2)
* Math.pow(Math.sin(mdifference / patm), patm)));
distance = distance * EARTH_RADIUS;
String distanceStr = String.valueOf(distance);
return distanceStr;
}
/**
* 获取当前用户一定距离以内的经纬度值
* 单位米 return minLat
* 最小经度 minLng
* 最小纬度 maxLat
* 最大经度 maxLng
* 最大纬度 minLat
*/
public static Map getAround(String latStr, String lngStr, String raidus) {
Map map = new HashMap();
Double latitude = Double.parseDouble(latStr);// 传值给经度
Double longitude = Double.parseDouble(lngStr);// 传值给纬度
Double degree = (24901 * 1609) / 360.0; // 获取每度
double raidusMile = Double.parseDouble(raidus);
Double mpdLng = Double.parseDouble((degree * Math.cos(latitude * (Math.PI / 180))+"").replace("-", ""));
Double dpmLng = 1 / mpdLng;
Double radiusLng = dpmLng * raidusMile;
//获取最小经度
Double minLat = longitude - radiusLng;
// 获取最大经度
Double maxLat = longitude + radiusLng;
Double dpmLat = 1 / degree;
Double radiusLat = dpmLat * raidusMile;
// 获取最小纬度
Double minLng = latitude - radiusLat;
// 获取最大纬度
Double maxLng = latitude + radiusLat;
map.put("minLat", minLat+"");
map.put("maxLat", maxLat+"");
map.put("minLng", minLng+"");
map.put("maxLng", maxLng+"");
return map;
}
public static void main(String[] args) {
//济南国际会展中心经纬度:117.11811 36.68484
//趵突泉:117.00999000000002 36.66123
System.out.println(getDistance("116.97265","36.694514","116.597805","36.738024"));
System.out.println(getAround("117.11811", "36.68484", "13000"));
//117.01028712333508(Double), 117.22593287666493(Double),
//36.44829619896034(Double), 36.92138380103966(Double)
}
}
package com.platform.utils.util;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* 从EXCEL导入到数据库
* @version
*/
public class ObjectExcelRead {
/**
* @param filepath //文件路径
* @param filename //文件名
* @param startrow //开始行号
* @param startcol //开始列号
* @param sheetnum //sheet
* @return list
*/
public static List<Object> readExcel(String filepath, String filename, int startrow, int startcol, int sheetnum) {
List<Object> varList = new ArrayList<Object>();
try {
File target = new File(filepath, filename);
FileInputStream fi = new FileInputStream(target);
HSSFWorkbook wb = new HSSFWorkbook(fi);
HSSFSheet sheet = wb.getSheetAt(sheetnum); //sheet 从0开始
int rowNum = sheet.getLastRowNum() + 1; //取得最后一行的行号
for (int i = startrow; i < rowNum; i++) { //行循环开始
Map varpd = new HashMap<>();
HSSFRow row = sheet.getRow(i); //行
int cellNum = row.getLastCellNum(); //每行的最后一个单元格位置
for (int j = startcol; j < cellNum; j++) { //列循环开始
HSSFCell cell = row.getCell(Short.parseShort(j + ""));
String cellValue = null;
if (null != cell) {
switch (cell.getCellType()) { // 判断excel单元格内容的格式,并对其进行转换,以便插入数据库
case 0:
cellValue = String.valueOf((int) cell.getNumericCellValue());
break;
case 1:
cellValue = cell.getStringCellValue();
break;
case 2:
cellValue = cell.getNumericCellValue() + "";
// cellValue = String.valueOf(cell.getDateCellValue());
break;
case 3:
cellValue = "";
break;
case 4:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case 5:
cellValue = String.valueOf(cell.getErrorCellValue());
break;
}
} else {
cellValue = "";
}
varpd.put("var"+j, cellValue);
}
varList.add(varpd);
}
} catch (Exception e) {
System.out.println(e);
}
return varList;
}
}
package com.platform.utils.util;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;
/**
* 导入到EXCEL
* @version 1.0
*/
public class ObjectExcelView extends AbstractExcelView{
@Override
protected void buildExcelDocument(Map<String, Object> model,
HSSFWorkbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
Date date = new Date();
String filename = Tools.date2Str(date, "yyyyMMddHHmmss");
HSSFSheet sheet;
HSSFCell cell;
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="+filename+".xls");
sheet = workbook.createSheet("sheet1");
List<String> titles = (List<String>) model.get("titles");
int len = titles.size();
HSSFCellStyle headerStyle = workbook.createCellStyle(); //标题样式
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
HSSFFont headerFont = workbook.createFont(); //标题字体
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerFont.setFontHeightInPoints((short)11);
headerStyle.setFont(headerFont);
short width = 20,height=25*20;
sheet.setDefaultColumnWidth(width);
for(int i=0; i<len; i++){ //设置标题
String title = titles.get(i);
cell = getCell(sheet, 0, i);
cell.setCellStyle(headerStyle);
setText(cell,title);
}
sheet.getRow(0).setHeight(height);
HSSFCellStyle contentStyle = workbook.createCellStyle(); //内容样式
contentStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
List<Map<String,Object>> varList = (List<Map<String,Object>>) model.get("varList");
int varCount = varList.size();
for(int i=0; i<varCount; i++){
Map<String,Object> vpd = varList.get(i);
for(int j=0;j<len;j++){
String varstr = vpd.get("var"+(j+1)) != null ? vpd.get("var"+(j+1)).toString() : "";
cell = getCell(sheet, i+1, j);
cell.setCellStyle(contentStyle);
setText(cell,varstr);
}
}
}
}
package com.platform.utils.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
public class OssUtil {
//////////阿里云要求jdom使用1.1版本!!!!!!!!!!!!!
//阿里云API的内或外网域名
private static final String ENDPOINT="oss-cn-shenzhen.aliyuncs.com";
//阿里云API的密钥Access Key ID
private static final String ACCESS_KEY_ID="5d6h34keSd9K3l2x";
//阿里云API的密钥Access Key Secret
private static final String ACCESS_KEY_SECRET="l2dJ4LpY6D6qV3jj3iQif7EPByoVQE";
//阿里云API的bucket名称
private static final String BACKET_NAME="diaosaas-prod";
//阿里云API的文件夹名称
private static final String FOLDER="education/";
/**
* 获取阿里云OSS客户端对象
* @return
*/
public static OSSClient getOSSClient(){
return new OSSClient(ENDPOINT,ACCESS_KEY_ID, ACCESS_KEY_SECRET);
}
/**
* 创建存储空间
* @param ossClient
* @param bucketName
* @return
*/
public static String createBucketName(OSSClient ossClient,String bucketName){
//存储空间
final String bucketNames=bucketName;
if(!ossClient.doesBucketExist(bucketName)){
//创建存储空间
Bucket bucket=ossClient.createBucket(bucketName);
return bucket.getName();
}
return bucketNames;
}
/**
* 删除存储空间
* @param ossClient
* @param bucketName
*/
public static void deleteBucket(OSSClient ossClient, String bucketName){
ossClient.deleteBucket(bucketName);
}
/**
* 创建模拟文件夹
* @param ossClient oss连接
* @param bucketName 存储空间
* @param folder 模拟文件夹名如"wenjianjia/"
* @return
*/
public static String createFolder(OSSClient ossClient,String bucketName,String folder){
//文件夹名
final String keySuffixWithSlash =folder;
//判断文件夹是否存在,不存在则创建
if(!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)){
//创建文件夹
ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0])); ;
//得到文件夹名
OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
String fileDir=object.getKey();
return fileDir;
}
return keySuffixWithSlash;
}
/**
* 根据key和folder删除OSS服务器上的文件
* @param bucketName bucketName存储空间
* @param folder folder模拟文件夹名 如"qj_nanjing/"
* @param key Bucket下的文件的路径名+文件名 如:"upload/cake.jpg"
*/
public static String deleteFile(String bucketName, String folder, String key){
OSSClient ossClient=getOSSClient();
try {
ossClient.deleteObject(bucketName, folder + key);
return "success";
} catch (Exception e) {
e.printStackTrace();
return "fail";
}finally {
ossClient.shutdown();
}
}
/**
* 根据key删除OSS服务器上的文件
* @param bucketName bucketName存储空间
* @param key Bucket下的文件的路径名+文件名 如:"upload/cake.jpg"
*/
public static String deleteFile(String bucketName, String key) {
OSSClient ossClient=getOSSClient();
try {
ossClient.deleteObject(bucketName,key);
return "success";
} catch (Exception e) {
e.printStackTrace();
return "fail";
}finally {
ossClient.shutdown();
}
}
/**
* 上传图片至OSS
* @param file
* @return
*/
public static String uploadObject2OSS(File file) {
OSSClient ossClient=getOSSClient();
try {
//以输入流的形式上传文件
InputStream is = new FileInputStream(file);
String path = file.getName();
String fileName =path.substring(path.lastIndexOf("//")+1);
String type=path.substring(path.lastIndexOf(".")+1);
int random = (int)(Math.random()*900)+10000;
//文件名
String fileNameNew = fileName.replace(fileName, String.valueOf(System.currentTimeMillis())+String.valueOf(random)+"."+type);
//文件大小
Long fileSize = file.length();
//创建上传Object的Metadata
ObjectMetadata metadata = new ObjectMetadata();
//上传的文件的长度
metadata.setContentLength(is.available());
//指定该Object被下载时的网页的缓存行为
metadata.setCacheControl("no-cache");
//指定该Object下设置Header
metadata.setHeader("Pragma", "no-cache");
//指定该Object被下载时的内容编码格式
metadata.setContentEncoding("utf-8");
//文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
//如果没有扩展名则填默认值application/octet-stream
metadata.setContentType(getContentType(fileNameNew));
//指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
metadata.setContentDisposition("filename/filesize=" + fileNameNew + "/" + fileSize + "Byte.");
System.out.println(FOLDER + fileNameNew);
//上传文件 (上传文件流的形式)
PutObjectResult putResult = ossClient.putObject(BACKET_NAME, FOLDER + fileNameNew, is, metadata);
//解析结果
URL url = getUrl(ossClient,putResult.getETag());
return "https://"+BACKET_NAME+"."+ENDPOINT+"/"+FOLDER+fileNameNew;
} catch (Exception e) {
e.printStackTrace();
return "fail";
} finally {
ossClient.shutdown();
}
//return url;
}
/**
* 上传视频至OSS(此方法用于课程管理模块)
*
* @param file
* @return
*/
public static String uploadObject3OSS(File file, String oldFileName) {
OSSClient ossClient = getOSSClient();
try {
// 以输入流的形式上传文件
InputStream is = new FileInputStream(file);
String path = file.getName();
System.out.println("path = " + path);
String fileName = path.substring(path.lastIndexOf("//") + 1);
System.out.println("fileName = " + fileName);
String type = path.substring(path.lastIndexOf(".") + 1);
int random = (int) (Math.random() * 900) + 10000;
// 文件名
String fileNameNew = fileName.replace(fileName,
String.valueOf(System.currentTimeMillis()) + String.valueOf(random) + "-"
+ oldFileName.substring(0, oldFileName.lastIndexOf(".")) + "."
+ type);
// 文件大小
Long fileSize = file.length();
// 创建上传Object的Metadata
ObjectMetadata metadata = new ObjectMetadata();
// 上传的文件的长度
metadata.setContentLength(is.available());
// 指定该Object被下载时的网页的缓存行为
metadata.setCacheControl("no-cache");
// 指定该Object下设置Header
metadata.setHeader("Pragma", "no-cache");
// 指定该Object被下载时的内容编码格式
metadata.setContentEncoding("utf-8");
// 文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
// 如果没有扩展名则填默认值application/octet-stream
metadata.setContentType(getContentType(fileNameNew));
// 指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
metadata.setContentDisposition("filename/filesize=" + fileNameNew + "/" + fileSize + "Byte.");
// 上传文件 (上传文件流的形式)
PutObjectResult putResult = ossClient.putObject(BACKET_NAME, FOLDER + fileNameNew, is, metadata);
// 解析结果
URL url = getUrl(ossClient, putResult.getETag());
System.out.println("fileNameNew= " + fileNameNew);
return "https://" + BACKET_NAME + "." + ENDPOINT + "/" + FOLDER + fileNameNew;
} catch (Exception e) {
e.printStackTrace();
return "fail";
} finally {
ossClient.shutdown();
}
// return url;
}
/**
* 上传图片至OSS
* @param file
* @return
*/
/**
* 上传图片至OSS
* @param file
* @return
*/
public static String uploadObject2OSS(byte[] byteArray) {
OSSClient ossClient=getOSSClient();
try {
InputStream is = new ByteArrayInputStream(byteArray);
//文件名
String fileNameNew = UuidUtil.get32UUID()+".png";
//文件大小
Long fileSize = Long.valueOf(byteArray.length);
//创建上传Object的Metadata
ObjectMetadata metadata = new ObjectMetadata();
//上传的文件的长度
metadata.setContentLength(is.available());
//指定该Object被下载时的网页的缓存行为
metadata.setCacheControl("no-cache");
//指定该Object下设置Header
metadata.setHeader("Pragma", "no-cache");
//指定该Object被下载时的内容编码格式
metadata.setContentEncoding("utf-8");
//文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
//如果没有扩展名则填默认值application/octet-stream
metadata.setContentType(getContentType(fileNameNew));
//指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
metadata.setContentDisposition("filename/filesize=" + fileNameNew + "/" + fileSize + "Byte.");
System.out.println(FOLDER + fileNameNew);
//上传文件 (上传文件流的形式)
PutObjectResult putResult = ossClient.putObject(BACKET_NAME, FOLDER + fileNameNew, is, metadata);
//解析结果
URL url = getUrl(ossClient,putResult.getETag());
return "https://"+BACKET_NAME+"."+ENDPOINT+"/"+FOLDER+fileNameNew;
} catch (Exception e) {
e.printStackTrace();
return "fail";
} finally {
ossClient.shutdown();
}
//return url;
}
/**
* 通过文件名判断并获取OSS服务文件上传时文件的contentType
* @param fileName
* @return
*/
public static String getContentType(String fileName){
//文件的后缀名
String fileExtension = fileName.substring(fileName.lastIndexOf("."));
if(".bmp".equalsIgnoreCase(fileExtension)) {
return "image/bmp";
}
if(".gif".equalsIgnoreCase(fileExtension)) {
return "image/gif";
}
if(".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)|| ".png".equalsIgnoreCase(fileExtension) ) {
return "image/jpeg";
}
if(".html".equalsIgnoreCase(fileExtension)) {
return "text/html";
}
if(".txt".equalsIgnoreCase(fileExtension)) {
return "text/plain";
}
if(".vsd".equalsIgnoreCase(fileExtension)) {
return "application/vnd.visio";
}
if(".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
return "application/vnd.ms-powerpoint";
}
if(".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
return "application/msword";
}
if(".xml".equalsIgnoreCase(fileExtension)) {
return "text/xml";
}
if (".mp4".equalsIgnoreCase(fileExtension)) {
return "video/mpeg4";
}
if (".avi".equalsIgnoreCase(fileExtension)) {
return "video/avi";
}
if (".asf".equalsIgnoreCase(fileExtension)) {
return "video/x-ms-asf";
}
if (".asx".equalsIgnoreCase(fileExtension)) {
return "video/x-ms-asf";
}
if (".IVF".equalsIgnoreCase(fileExtension)) {
return "video/x-ivf";
}
if (".m2v".equalsIgnoreCase(fileExtension)) {
return "video/x-mpeg";
}
if (".m4e".equalsIgnoreCase(fileExtension)) {
return "video/mpeg4";
}
if (".m1v".equalsIgnoreCase(fileExtension)) {
return "video/x-mpeg";
}
if (".wmv".equalsIgnoreCase(fileExtension)) {
return "video/x-ms-wmv";
}
if (".wmx".equalsIgnoreCase(fileExtension)) {
return "video/x-ms-wmx";
}
if (".wvx".equalsIgnoreCase(fileExtension)) {
return "video/x-ms-wvx";
}
if (".mpv".equalsIgnoreCase(fileExtension)) {
return "video/mpg";
}
//默认返回类型
return "image/jpeg";
}
/**
*
* @param ossClient
* @param key
* @return
*/
public static URL getUrl(OSSClient ossClient,String key) {
// 设置URL过期时间为10年
Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
// 生成URL
URL url = ossClient.generatePresignedUrl(BACKET_NAME, key, expiration);
return url;
}
/**
* 上传的方法
* @author LHB
* @since JDK 1.8
*/
public static String upload(MultipartFile file) throws Exception{
String fileName = file.getOriginalFilename();
String prefix=fileName.substring(fileName.lastIndexOf("."));
final File realfile = File.createTempFile(UuidUtil.get32UUID(), prefix);
file.transferTo(realfile);
String url=OssUtil.uploadObject2OSS(realfile);
System.out.println(url);
return url;
}
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
}
package com.platform.utils.util;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
/**
* 说明:参数封装Map
* @version
*/
public class PageData extends HashMap implements Map{
private static final long serialVersionUID = 1L;
Map map = null;
HttpServletRequest request;
public PageData(HttpServletRequest request){
this.request = request;
Map properties = request.getParameterMap();
Map returnMap = new HashMap();
Iterator entries = properties.entrySet().iterator();
Entry entry;
String name = "";
String value = "";
while (entries.hasNext()) {
entry = (Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
value = values[i] + ",";
}
value = value.substring(0, value.length()-1);
}else{
value = valueObj.toString();
}
returnMap.put(name, value);
}
map = returnMap;
}
public PageData() {
map = new HashMap();
}
@Override
public Object get(Object key) {
Object obj = null;
if(map.get(key) instanceof Object[]) {
Object[] arr = (Object[])map.get(key);
obj = request == null ? arr:(request.getParameter((String)key) == null ? arr:arr[0]);
} else {
obj = map.get(key);
}
return obj;
}
public String getString(Object key) {
return (String)get(key);
}
@SuppressWarnings("unchecked")
@Override
public Object put(Object key, Object value) {
return map.put(key, value);
}
@Override
public Object remove(Object key) {
return map.remove(key);
}
public void clear() {
map.clear();
}
public boolean containsKey(Object key) {
// TODO Auto-generated method stub
return map.containsKey(key);
}
public boolean containsValue(Object value) {
// TODO Auto-generated method stub
return map.containsValue(value);
}
public Set entrySet() {
// TODO Auto-generated method stub
return map.entrySet();
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return map.isEmpty();
}
public Set keySet() {
// TODO Auto-generated method stub
return map.keySet();
}
@SuppressWarnings("unchecked")
public void putAll(Map t) {
// TODO Auto-generated method stub
map.putAll(t);
}
public int size() {
// TODO Auto-generated method stub
return map.size();
}
public Collection values() {
// TODO Auto-generated method stub
return map.values();
}
}
package com.platform.utils.util;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* 说明:路径工具类
* @version
*/
public class PathUtil {
/**
* 图片访问路径
* @param pathType
* 图片类型 visit-访问;save-保存
* @param pathCategory
* 图片类别,如:话题图片-topic、话题回复图片-reply、商家图片
* @return
*/
public static String getPicturePath(String pathType, String pathCategory) {
String strResult = "";
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
StringBuffer strBuf = new StringBuffer();
if ("visit".equals(pathType)) {
} else if ("save".equals(pathType)) {
String projectPath = PublicUtil.getPorjectPath().replaceAll("\\\\",
"/");
projectPath = splitString(projectPath, "bin/");
strBuf.append(projectPath);
strBuf.append("webapps/ROOT/");
}
strResult = strBuf.toString();
return strResult;
}
private static String splitString(String str, String param) {
String result = str;
if (str.contains(param)) {
int start = str.indexOf(param);
result = str.substring(0, start);
}
return result;
}
/**获取classpath1
* @return
*/
public static String getClasspath(){
String path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../").replaceAll("file:/", "").replaceAll("%20", " ").trim();
if(path.indexOf(":") != 1){
path = File.separator + path;
}
return path;
}
/**获取classpath2
* @return
*/
public static String getClassResources(){
String path = (String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))).replaceAll("file:/", "").replaceAll("%20", " ").trim();
if(path.indexOf(":") != 1){
path = File.separator + path;
}
return path;
}
public static String PathAddress() {
String strResult = "";
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
StringBuffer strBuf = new StringBuffer();
strBuf.append(request.getScheme() + "://");
strBuf.append(request.getServerName() + ":");
strBuf.append(request.getServerPort() + "");
strBuf.append(request.getContextPath() + "/");
strResult = strBuf.toString();// +"ss/";//加入项目的名称
return strResult;
}
}
package com.platform.utils.util;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* 说明:IP处理
* @version
*/
public class PublicUtil {
public static void main(String[] args) {
System.out.println("本机的ip=" + PublicUtil.getIp());
}
public static String getPorjectPath(){
String nowpath = "";
nowpath=System.getProperty("user.dir")+"/";
return nowpath;
}
/**
* 获取本机访问地址
* @return
*/
public static String getIp(){
String ip = "";
try {
InetAddress inet = InetAddress.getLocalHost();
ip = inet.getHostAddress();
//System.out.println("本机的ip=" + ip);
} catch (UnknownHostException e) {
e.printStackTrace();
}
return ip;
}
}
\ No newline at end of file
package com.platform.utils.util.QRCodeImage;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.EnumMap;
import javax.imageio.ImageIO;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
/**
* @ClassName DecodeImgZxing
* @Description 通过google的zxing解析二维码 注:此代码,不能解析:L纠错级别带logo和H级别的解析
* @author 林海冰
* @version 广州抵奥云信息科技有限公司
* @since JDK 1.8
* @see 二维码解析
*/
public class DecodeImgZxing {
//二维码格式参数
private static final EnumMap<DecodeHintType, Object> hints = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);
static{
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
}
/**
* 解析二维码,使用google的zxing
* @param imgPath 二维码路径
* @return content 二维码内容
* */
public static String decodeImg(File imgFile){
String content = null;
if(!imgFile.isFile()){
System.out.println("输入非文件");
return null;
}
try {
BufferedImage image = ImageIO.read(imgFile);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
MultiFormatReader reader = new MultiFormatReader();
Result result = reader.decode(binaryBitmap, hints);
content = result.getText();
// System.out.println("二维码结果:"+":"+result.toString()+","+result.getBarcodeFormat()+","+result.getText());
} catch (NotFoundException e) {
System.out.println("二维码解析NotFoundException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("二维码解析IOException");
e.printStackTrace();
}
return content;
}
}
package com.platform.utils.util.QRCodeImage;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
/**
* ClassName:EncodeImgZingLogo <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/>
* Date: 2019年1月17日 上午11:56:13 <br/>
* @author 林海冰
* @version 广州抵奥云信息科技有限公司
* @since JDK 1.8
* @see 带logo的二维码生成代码
*/
import javax.imageio.ImageIO;
public class EncodeImgZingLogo {
/**
* 二维码绘制logo
* @param twodimensioncodeImg 二维码图片文件
* @param logoImg logo图片文件
* */
public static BufferedImage encodeImgLogo(File twodimensioncodeImg, File logoImg){
BufferedImage twodimensioncode = null;
try{
if(!twodimensioncodeImg.isFile() || !logoImg.isFile()){
System.out.println("输入非图片");
return null;
}
//读取二维码图片
twodimensioncode = ImageIO.read(twodimensioncodeImg);
//获取画笔
Graphics2D g = twodimensioncode.createGraphics();
//读取logo图片
BufferedImage logo = ImageIO.read(logoImg);
//设置二维码大小,太大,会覆盖二维码,此处20%
int logoWidth = logo.getWidth(null) > twodimensioncode.getWidth()*2 /10 ? (twodimensioncode.getWidth()*2 /10) : logo.getWidth(null);
int logoHeight = logo.getHeight(null) > twodimensioncode.getHeight()*2 /10 ? (twodimensioncode.getHeight()*2 /10) : logo.getHeight(null);
//设置logo图片放置位置
//中心
int x = (twodimensioncode.getWidth() - logoWidth) / 2;
int y = (twodimensioncode.getHeight() - logoHeight) / 2;
//右下角,15为调整值
// int x = twodimensioncode.getWidth() - logoWidth-15;
// int y = twodimensioncode.getHeight() - logoHeight-15;
//开始合并绘制图片
g.drawImage(logo, x, y, logoWidth, logoHeight, null);
g.drawRoundRect(x, y, logoWidth, logoHeight, 15 ,15);
//logo边框大小
g.setStroke(new BasicStroke(2));
//logo边框颜色
g.setColor(Color.WHITE);
g.drawRect(x, y, logoWidth, logoHeight);
g.dispose();
logo.flush();
twodimensioncode.flush();
}catch(Exception e){
System.out.println("二维码绘制logo失败");
}
return twodimensioncode;
}
/**
* 二维码输出到文件
* @param twodimensioncodeImg 二维码图片文件
* @param logoImg logo图片文件
* @param format 图片格式
* @param file 输出文件
* */
public static void writeToFile(File twodimensioncodeImg,File logoImg,String format,File file) throws IOException {
BufferedImage image = encodeImgLogo(twodimensioncodeImg, logoImg);
try {
ImageIO.write(image, format, file);
} catch (IOException e) {
System.out.println("二维码写入文件失败"+e.getMessage());
}
}
/**
* 二维码流式输出
* @param twodimensioncodeImg 二维码图片文件
* @param logoImg logo图片文件
* @param format 图片格式
* @param stream 输出流
* */
public static void writeToStream(File twodimensioncodeImg,File logoImg,String format,OutputStream stream){
BufferedImage image = encodeImgLogo(twodimensioncodeImg, logoImg);
try {
ImageIO.write(image, format, stream);
} catch (IOException e) {
System.out.println("二维码写入流失败"+e.getMessage());
}
}
}
package com.platform.utils.util.QRCodeImage;
import java.io.File;
import java.io.IOException;
/**
* ClassName:EncodeImgZingLogoTest <br/>
* Date: 2019年1月17日 下午12:10:14 <br/>
* @author 林海冰
* @version 广州抵奥云信息科技有限公司
* @since JDK 1.8
* @see 二维码生成器工具测试类
*/
public class EncodeImgZingLogoTest {
public static void main(String[] args) throws IOException {
String contents = "https://blog.csdn.net/shasiqq/article/details/80307846";
String format = "jpg"; //***此处如果格式为"gif",则logo图片为黑色,其他格式ok
//生成二维码
File img = new File("D:"+File.separator+"csdn.jpg");
EncodeImgZxing.writeToFile(contents, format, img);
//生成带有logo图片的二维码
File logoImg = new File("D:"+File.separator+"logo.jpg");
File img1 = new File("D:"+File.separator+"csdnAndLogo.jpg");
EncodeImgZingLogo.writeToFile(img, logoImg, format, img1);
//解析二维码内容
String content = DecodeImgZxing.decodeImg(img);
System.out.println("1:"+content);
//解析二维码带logo内容
String content1 = DecodeImgZxing.decodeImg(img1);
System.out.println("2:"+content1);
}
}
package com.platform.utils.util.QRCodeImage;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.EnumMap;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* ClassName:EncodeImgZxing <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/>
* Date: 2019年1月17日 上午11:55:40 <br/>
* @author 林海冰
* @version 广州抵奥云信息科技有限公司
* @since JDK 1.8
* @see 生成二维码准备文件
*/
public class EncodeImgZxing {
//二维码颜色
private static final int BLACK = 0xFF000000;//0xFFFF0000,红色
//二维码背景色
private static final int WHITE = 0xFFFFFFFF;//0xFF0000FF,蓝色
//注:二维码颜色色差大,扫描快,但如果"BLACK'设置为黑色外其他颜色,可能无法扫描
//二维码图片宽度
private static final int width = 300;
//二维码图片高度
private static final int height = 300;
//二维码格式参数
private static final EnumMap<EncodeHintType, Object> hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
static{
/*二维码的纠错级别(排错率),4个级别:
L (7%)、
M (15%)、
Q (25%)、
H (30%)(最高H)
纠错信息同样存储在二维码中,纠错级别越高,纠错信息占用的空间越多,那么能存储的有用讯息就越少;共有四级;
选择M,扫描速度快。
*/
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 二维码边界空白大小 1,2,3,4 (4为默认,最大)
hints.put(EncodeHintType.MARGIN, 1);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MAX_SIZE, 350);
hints.put(EncodeHintType.MIN_SIZE, 150);
}
/**
* 绘制二维码
* @param contents 二维码内容
* @return image 二维码图片
* */
public static BufferedImage encodeImg(String contents){
BufferedImage image = null;
try{
BitMatrix matrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int width = matrix.getWidth();
int height = matrix.getHeight();
for(int x = 0; x < width; x++){
for(int y =0;y < height; y++){
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
}catch(Exception e){
System.out.println("生成二维码失败"+e.getMessage());
}
return image;
}
/**
* 二维码输出到文件
* @param contents 二维码内容
* @param format 图片格式
* @param file 输出文件
* */
public static void writeToFile(String contents,String format,File file){
BufferedImage image = encodeImg(contents);
try {
ImageIO.write(image, format, file);
} catch (IOException e) {
System.out.println("二维码写入文件失败"+e.getMessage());
}
}
/**
* 二维码流式输出
* @param contents 二维码内容
* @param format 图片格式
* @param stream 输出流
* */
public static void writeToStream(String contents,String format,OutputStream stream){
BufferedImage image = encodeImg(contents);
try {
ImageIO.write(image, format, stream);
} catch (IOException e) {
System.out.println("二维码写入流失败"+e.getMessage());
}
}
}
package com.platform.utils.util;
import java.lang.reflect.Field;
/**
* 说明:反射工具
* @version
*/
public class ReflectHelper {
/**
* 获取obj对象fieldName的Field
* @param obj
* @param fieldName
* @return
*/
public static Field getFieldByFieldName(Object obj, String fieldName) {
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
.getSuperclass()) {
try {
return superClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
}
}
return null;
}
/**
* 获取obj对象fieldName的属性值
* @param obj
* @param fieldName
* @return
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static Object getValueByFieldName(Object obj, String fieldName)
throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field field = getFieldByFieldName(obj, fieldName);
Object value = null;
if(field!=null){
if (field.isAccessible()) {
value = field.get(obj);
} else {
field.setAccessible(true);
value = field.get(obj);
field.setAccessible(false);
}
}
return value;
}
/**
* 设置obj对象fieldName的属性值
* @param obj
* @param fieldName
* @param value
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static void setValueByFieldName(Object obj, String fieldName,
Object value) throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
Field field = obj.getClass().getDeclaredField(fieldName);
if (field.isAccessible()) {
field.set(obj, value);
} else {
field.setAccessible(true);
field.set(obj, value);
field.setAccessible(false);
}
}
}
package com.platform.utils.util;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class RequestUtil {
public static String getValue(){
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
// Map pd = new HashMap<>();
// pd.putAll((Map) request);
Map properties = request.getParameterMap();
Map returnMap = new HashMap();
Iterator entries = properties.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
while (entries.hasNext()) {
entry = (Map.Entry) entries.next();
name = (String) entry.getKey();
}
return name;
}
}
\ No newline at end of file
package com.platform.utils.util;
import java.io.Serializable;
public class ResultOutDto implements Serializable{
private static final long serialVersionUID = 1L;
public final static int flag_success = 1;
public final static int flag_fail = 0;
public final static int flag_error = -1;
int flag;
String errmsg;
Object data;
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
public Object getData() {
return data;
}
public void setData(Object data2) {
this.data = data2;
}
public static ResultOutDto ok(){
ResultOutDto resultOutDto = new ResultOutDto();
resultOutDto.setFlag(flag_success);
return resultOutDto;
}
public static ResultOutDto ok(Object data){
ResultOutDto resultOutDto = new ResultOutDto();
resultOutDto.setFlag(flag_success);
resultOutDto.setData(data);
return resultOutDto;
}
public static ResultOutDto err(Object data,String err){
ResultOutDto resultOutDto = new ResultOutDto();
resultOutDto.setFlag(flag_fail);
resultOutDto.setData(data);
resultOutDto.setErrmsg(err);
return resultOutDto;
}
public static ResultOutDto err(String err){
ResultOutDto resultOutDto = new ResultOutDto();
resultOutDto.setFlag(flag_fail);
resultOutDto.setData(null);
resultOutDto.setErrmsg(err);
return resultOutDto;
}
}
package com.platform.utils.util;
import java.math.BigInteger;
/**
* 权限计算帮助类
*/
public class RightsHelper {
/**
* 利用BigInteger对权限进行2的权的和计算
* @param rights int型权限编码数组
* @return 2的权的和
*/
public static BigInteger sumRights(int[] rights){
BigInteger num = new BigInteger("0");
for(int i=0; i<rights.length; i++){
num = num.setBit(rights[i]);
}
return num;
}
/**
* 利用BigInteger对权限进行2的权的和计算
* @param rights String型权限编码数组
* @return 2的权的和
*/
public static BigInteger sumRights(String[] rights){
BigInteger num = new BigInteger("0");
for(int i=0; i<rights.length; i++){
num = num.setBit(Integer.parseInt(rights[i]));
}
return num;
}
/**
* 测试是否具有指定编码的权限
* @param sum
* @param targetRights
* @return
*/
public static boolean testRights(BigInteger sum,int targetRights){
return sum.testBit(targetRights);
}
/**
* 测试是否具有指定编码的权限
* @param sum
* @param targetRights
* @return
*/
public static boolean testRights(String sum,int targetRights){
if(Tools.isEmpty(sum))
return false;
return testRights(new BigInteger(sum),targetRights);
}
/**
* 测试是否具有指定编码的权限
* @param sum
* @param targetRights
* @return
*/
public static boolean testRights(String sum,String targetRights){
if(Tools.isEmpty(sum))
return false;
return testRights(new BigInteger(sum),targetRights);
}
/**
* 测试是否具有指定编码的权限
* @param sum
* @param targetRights
* @return
*/
public static boolean testRights(BigInteger sum,String targetRights){
return testRights(sum,Integer.parseInt(targetRights));
}
}
package com.platform.utils.util;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* 短信接口类
* @author lyl
*
* 2018年4月18日
*/
public class SMSUtil {
//查账户信息的http地址
private static String URI_GET_USER_INFO = "https://sms.yunpian.com/v2/user/get.json";
//模板发送接口的http地址
private static String URI_TPL_SEND_SMS = "https://sms.yunpian.com/v2/sms/tpl_single_send.json";
//编码格式。发送编码格式统一用UTF-8
private static String ENCODING = "UTF-8";
/**
* 查询用户信息
*
* @param apikey
* @return
* @throws IOException
* @throws URISyntaxException
*/
public static String getUserInfo(String apikey) throws IOException, URISyntaxException {
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", apikey);
return post(URI_GET_USER_INFO, params);
}
/**
* 提交响应
*
* @param url
* @param paramsMap
* @return
*/
public static String post(String url, Map<String, String> paramsMap) {
CloseableHttpClient client = HttpClients.createDefault();
String responseText = "";
CloseableHttpResponse response = null;
try {
HttpPost method = new HttpPost(url);
if (paramsMap != null) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> param : paramsMap.entrySet()) {
NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
paramList.add(pair);
}
method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
}
response = client.execute(method);
HttpEntity entity = response.getEntity();
if (entity != null) {
responseText = EntityUtils.toString(entity, ENCODING);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return responseText;
}
/**
* 发送验证码
*
* @return
* @throws IOException
*/
public String yzCode(String phone) throws IOException{
if(phone.equals(null)){
return "error";
}
//编码格式。发送编码格式统一用UTF-8
String ENCODING = "UTF-8";
String apikey = "8f0bf6adf28e6adb559c158bb448909e";//APIKey
long tpl_id = 1;//模板ID
String code = RandomStringUtils.randomNumeric(6);// 生成6位随机验证码
String tpl_value = URLEncoder.encode("#code#",ENCODING) +"="
+ URLEncoder.encode(code, ENCODING) + "&"
+ URLEncoder.encode("#company#",ENCODING) + "="
+ URLEncoder.encode("正品2020",ENCODING);
System.out.println(tpl_value);
System.out.println(SMSUtil.tplSendSms(apikey, tpl_id, tpl_value, phone));
return code;
}
public String yzCode(String phone,String hour ) throws IOException{
if(phone.equals(null)){
return "error";
}
//编码格式。发送编码格式统一用UTF-8
String ENCODING = "UTF-8";
String apikey = "8f0bf6adf28e6adb559c158bb448909e";//APIKey
long tpl_id = 2894586;//模板ID
String code = RandomStringUtils.randomNumeric(6);// 生成6位随机验证码
String tpl_value =
URLEncoder.encode("#code#",ENCODING) +"="
+ URLEncoder.encode(code, ENCODING)+"&"
+URLEncoder.encode("#hour#",ENCODING) +"="
+ URLEncoder.encode(hour, ENCODING);
System.out.println(tpl_value);
System.out.println(SMSUtil.tplSendSms(apikey, tpl_id, tpl_value, phone));
return code;
}
/**
* 通过模板发送短信
*
* @param apikey
* @param tpl_id
* @param tpl_value
* @param mobile
* @return
* @throws IOException
*/
public static String tplSendSms(String apikey, long tpl_id, String tpl_value, String mobile) throws IOException {
Map<String, String> params = new HashMap<String, String>();
params.put("apikey", apikey);
params.put("tpl_id", String.valueOf(tpl_id));
params.put("tpl_value", tpl_value);
params.put("mobile", mobile);
return post(URI_TPL_SEND_SMS, params);
}
public static void main(String[] args) throws IOException {
SMSUtil smsUtil = new SMSUtil();
smsUtil.yzCode("15913115046");
}
}
package com.platform.utils.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
public class SerialNumUtil {
private static String count = "000";
private static String dateValue = "20131115";
/**
* 产生流水号
*/
public synchronized static String getMoveOrderNo() {
long No = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String nowdate = sdf.format(new Date());
No = Long.parseLong(nowdate);
if (!(String.valueOf(No)).equals(dateValue)) {
count = "000";
dateValue = String.valueOf(No);
}
String num = String.valueOf(No);
num += getNo(count);
num = "DD" + num;
return num;
}
/**
* 获取撤展单序列号
*/
public synchronized static String getMoveOrderNo(String serialNum) {
String nyr = StringUtils.substring(serialNum, 2, 10); // 获取年月日字符串
String countV = StringUtils.substring(serialNum, 10); // 获取流水号
if (Integer.valueOf(countV) > Integer.valueOf(count)) {
dateValue = nyr;
count = String.valueOf(countV);
}
return getMoveOrderNo();
}
/**
* 返回当天的订单数+1
*/
public static String getNo(String s) {
String rs = s;
int i = Integer.parseInt(rs);
i += 1;
rs = "" + i;
for (int j = rs.length(); j < 3; j++) {
rs = "0" + rs;
}
count = rs;
return rs;
}
public static void main(String[] args) {
System.out.println(getMoveOrderNo("DD20180320001"));
}
}
package com.platform.utils.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
/**
* 说明:list排序
* 修改时间:2015年11月24日
* @version
*/
public class SortUtil {
public static void main(String[] args) {
System.out.println(testMapSort());
}
/**
* 对list进行排序
* @param sortList 需要排序的list
* @param param1 排序的参数名称
* @param orderType 排序类型:正序-asc;倒序-desc
*/
public static List<Object> sort(List<Object> sortList, String param1, String orderType){
Comparator<Object> mycmp1 = ComparableComparator.getInstance ();
if("desc".equals(orderType)){
mycmp1 = ComparatorUtils. reversedComparator(mycmp1); //逆序(默认为正序)
}
ArrayList<Object> sortFields = new ArrayList<Object>();
sortFields.add( new BeanComparator(param1 , mycmp1)); //主排序(第一排序)
ComparatorChain multiSort = new ComparatorChain(sortFields);
Collections.sort (sortList , multiSort);
return sortList;
}
/**
* 对list进行排序
* @param sortList 需要排序的list
* @param param1 排序的参数名称:参数长度
* @param param2 排序的参数名称:排序参数
* @param orderType 排序类型:正序-asc;倒序-desc
*/
public static List<Object> sortParam2(List<Object> sortList, String param1,String param2, String orderType){
Comparator<Object> mycmp1 = ComparableComparator.getInstance ();
Comparator<Object> mycmp2 = ComparableComparator.getInstance ();
if("desc".equals(orderType)){
mycmp1 = ComparatorUtils. reversedComparator(mycmp1); //逆序(默认为正序)
}
ArrayList<Object> sortFields = new ArrayList<Object>();
sortFields.add( new BeanComparator(param1 , mycmp1)); //主排序(第一排序)
sortFields.add( new BeanComparator(param2 , mycmp2)); //主排序(第一排序)
ComparatorChain multiSort = new ComparatorChain(sortFields);
Collections.sort (sortList , multiSort);
return sortList;
}
public static List<Object> testMapSort(){
//List<Object> sortList = new ArrayList<Object>();
Map map = new HashMap();
map.put("name", "1");
map.put("age", "1");
Map map2 = new HashMap();
map2.put("name", "2");
map2.put("age", "13");
Map map1 = new HashMap();
map1.put("name", "2");
map1.put("age", "12");
List<Object> list = new ArrayList();
list.add(map);
list.add(map1);
list.add(map2);
//return sort(list, "age", "asc");
return sortParam2(list, "name", "age", "asc");
}
}
package com.platform.utils.util;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring ApplicationContext 工具类
*/
@SuppressWarnings("unchecked")
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtils.applicationContext = applicationContext;
}
public static <T> T getBean(String beanName) {
if(applicationContext.containsBean(beanName)){
return (T) applicationContext.getBean(beanName);
}else{
return null;
}
}
public static <T> Map<String, T> getBeansOfType(Class<T> baseType){
return applicationContext.getBeansOfType(baseType);
}
}
package com.platform.utils.util;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*   
*
* @Title: StringHelper.java
* @Package com.jarvis.base.utils
* @Description:
* @author Jack 
* @date 2017年9月2日 下午2:23:51
* @version V1.0   字符串处理工具类。
*/
public final class StringHelper {
/**
* 描述: 构造方法
*/
private StringHelper() {
}
/**
* 空字符串
*/
public static final String EMPTY_STRING = "";
/**
* 点
*/
public static final char DOT = '.';
/**
* 下划线
*/
public static final char UNDERSCORE = '_';
/**
* 逗点及空格
*/
public static final String COMMA_SPACE = ", ";
/**
* 逗点
*/
public static final String COMMA = ",";
/**
* 开始括号
*/
public static final String OPEN_PAREN = "(";
/**
* 结束括号
*/
public static final String CLOSE_PAREN = ")";
/**
* 单引号
*/
public static final char SINGLE_QUOTE = '\'';
/**
* 回车
*/
public static final String CRLF = "\r\n";
/**
* 常量 12
*/
public static final int FIANL_TWELVE = 12;
/**
* 十六进制常量 0x80
*/
public static final int HEX_80 = 0x80;
/**
* 十六进制常量 0xff
*/
public static final int HEX_FF = 0xff;
/**
* 把字符数组,转化为一个字符
*
* @param seperator
* 字符分隔符
* @param strings
* 数组对象
* @return 字符串
*/
public static String join(String seperator, String[] strings) {
int length = strings.length;
if (length == 0) {
return EMPTY_STRING;
}
StringBuffer buf = new StringBuffer(length * strings[0].length()).append(strings[0]);
for (int i = 1; i < length; i++) {
buf.append(seperator).append(strings[i]);
}
return buf.toString();
}
/**
* 把迭代对象转化为一个字符串
*
* @param seperator
* 分隔符
* @param objects
* 迭代器对象
* @return 字符串
*/
public static String join(String seperator, Iterator<?> objects) {
StringBuffer buf = new StringBuffer();
if (objects.hasNext()) {
buf.append(objects.next());
}
while (objects.hasNext()) {
buf.append(seperator).append(objects.next());
}
return buf.toString();
}
/**
* 把两个字符串数组的元素用分隔符连接,生成新的数组,生成的数组以第一个字符串数组为参照,与其长度相同。
*
* @param x
* 字符串数组
* @param seperator
* 分隔符
* @param y
* 字符串数组
* @return 组合后的字符串数组
*/
public static String[] add(String[] x, String seperator, String[] y) {
String[] result = new String[x.length];
for (int i = 0; i < x.length; i++) {
result[i] = x[i] + seperator + y[i];
}
return result;
}
/**
* 生成一个重复的字符串,如需要重复*10次,则生成:**********。
*
* @param string
* 重复元素
* @param times
* 重复次数
* @return 生成后的字符串
*/
public static String repeat(String string, int times) {
StringBuffer buf = new StringBuffer(string.length() * times);
for (int i = 0; i < times; i++) {
buf.append(string);
}
return buf.toString();
}
/**
* 字符串替换处理,把旧的字符串替换为新的字符串,主要是通过字符串查找进行处理
*
* @param source
* 需要进行替换的字符串
* @param old
* 需要进行替换的字符串
* @param replace
* 替换成的字符串
* @return 替换处理后的字符串
*/
public static String replace(String source, String old, String replace) {
StringBuffer output = new StringBuffer();
int sourceLen = source.length();
int oldLen = old.length();
int posStart = 0;
int pos;
// 通过截取字符串的方式,替换字符串
while ((pos = source.indexOf(old, posStart)) >= 0) {
output.append(source.substring(posStart, pos));
output.append(replace);
posStart = pos + oldLen;
}
// 如果还有没有处理的字符串,则都添加到新字符串后面
if (posStart < sourceLen) {
output.append(source.substring(posStart));
}
return output.toString();
}
/**
* 替换字符,如果指定进行全替换,必须设wholeWords=true,否则只替换最后出现的字符。
*
* @param template
* 字符模板
* @param placeholder
* 需要替换的字符
* @param replacement
* 新的字符
* @param wholeWords
* 是否需要全替换,true为需要,false为不需要。如果不需要,则只替换最后出现的字符。
* @return 替换后的新字符
*/
public static String replace(String template, String placeholder, String replacement, boolean wholeWords) {
int loc = template.indexOf(placeholder);
if (loc < 0) {
return template;
} else {
final boolean actuallyReplace = wholeWords || loc + placeholder.length() == template.length()
|| !Character.isJavaIdentifierPart(template.charAt(loc + placeholder.length()));
String actualReplacement = actuallyReplace ? replacement : placeholder;
return new StringBuffer(template.substring(0, loc)).append(actualReplacement).append(
replace(template.substring(loc + placeholder.length()), placeholder, replacement, wholeWords))
.toString();
}
}
/**
* 替换字符,只替换第一次出现的字符串。
*
* @param template
* 字符模板
* @param placeholder
* 需要替换的字符串
* @param replacement
* 新字符串
* @return 替换后的字符串
*/
public static String replaceOnce(String template, String placeholder, String replacement) {
int loc = template.indexOf(placeholder);
if (loc < 0) {
return template;
} else {
return new StringBuffer(template.substring(0, loc)).append(replacement)
.append(template.substring(loc + placeholder.length())).toString();
}
}
/**
* 把字符串,按指字的分隔符分隔为字符串数组
*
* @param seperators
* 分隔符
* @param list
* 字符串
* @return 字符串数组
*/
public static String[] split(String list, String seperators) {
return split(list, seperators, false);
}
/**
* 把字符串,按指字的分隔符分隔为字符串数组
*
* @param seperators
* 分隔符
* @param list
* 字符串
* @param include
* 是否需要把分隔符也返回
* @return 字符串数组
*/
public static String[] split(String list, String seperators, boolean include) {
StringTokenizer tokens = new StringTokenizer(list, seperators, include);
String[] result = new String[tokens.countTokens()];
int i = 0;
while (tokens.hasMoreTokens()) {
result[i++] = tokens.nextToken();
}
return result;
}
/**
* 提取字符串中,以.为分隔符后的所有字符,如string.exe,将返回exe。
*
* @param qualifiedName
* 字符串
* @return 提取后的字符串
*/
public static String unqualify(String qualifiedName) {
return unqualify(qualifiedName, ".");
}
/**
* 提取字符串中,以指定分隔符后的所有字符,如string.exe,将返回exe。
*
* @param qualifiedName
* 字符串
* @param seperator
* 分隔符
* @return 提取后的字符串
*/
public static String unqualify(String qualifiedName, String seperator) {
return qualifiedName.substring(qualifiedName.lastIndexOf(seperator) + 1);
}
/**
* 提取字符串中,以.为分隔符以前的字符,如string.exe,则返回string
*
* @param qualifiedName
* 字符串
* @return 提取后的字符串
*/
public static String qualifier(String qualifiedName) {
int loc = qualifiedName.lastIndexOf(".");
if (loc < 0) {
return EMPTY_STRING;
} else {
return qualifiedName.substring(0, loc);
}
}
/**
* 向字符串数组中的所有元素添加上后缀
*
* @param columns
* 字符串数组
* @param suffix
* 后缀
* @return 添加后缀后的数组
*/
public static String[] suffix(String[] columns, String suffix) {
if (suffix == null) {
return columns;
}
String[] qualified = new String[columns.length];
for (int i = 0; i < columns.length; i++) {
qualified[i] = suffix(columns[i], suffix);
}
return qualified;
}
/**
* 向字符串加上后缀
*
* @param name
* 需要添加后缀的字符串
* @param suffix
* 后缀
* @return 添加后缀的字符串
*/
public static String suffix(String name, String suffix) {
return (suffix == null) ? name : name + suffix;
}
/**
* 向字符串数组中的所有元素,添加上前缀
*
* @param columns
* 需要添加前缀的字符串数组
* @param prefix
* prefix
* @return
*/
public static String[] prefix(String[] columns, String prefix) {
if (prefix == null) {
return columns;
}
String[] qualified = new String[columns.length];
for (int i = 0; i < columns.length; i++) {
qualified[i] = prefix + columns[i];
}
return qualified;
}
/**
* 向字符串添加上前缀
*
* @param name
* 需要添加前缀的字符串
* @param prefix
* 前缀
* @return 添加前缀后的字符串
*/
public static String prefix(String name, String prefix) {
return (prefix == null) ? name : prefix + name;
}
/**
* 判断字符串是否为"true"、"t",如果是,返回true,否则返回false
*
* @param tfString
* 需要进行判断真/假的字符串
* @return true/false
*/
public static boolean booleanValue(String tfString) {
String trimmed = tfString.trim().toLowerCase();
return trimmed.equals("true") || trimmed.equals("t");
}
/**
* 把对象数组转化为字符串
*
* @param array
* 对象数组
* @return 字符串
*/
public static String toString(Object[] array) {
int len = array.length;
if (len == 0) {
return StringHelper.EMPTY_STRING;
}
StringBuffer buf = new StringBuffer(len * FIANL_TWELVE);
for (int i = 0; i < len - 1; i++) {
buf.append(array[i]).append(StringHelper.COMMA_SPACE);
}
return buf.append(array[len - 1]).toString();
}
/**
* 描述:把数组中的所有元素出现的字符串进行替换,把旧字符串替换为新字符数组的所有元素,只替换第一次出现的字符。
*
* @param string
* 需要替换的数组
* @param placeholders
* 需要替换的字符串
* @param replacements
* 新字符串数组
* @return 替换后的字符串数组
*/
public static String[] multiply(String string, Iterator<?> placeholders, Iterator<?> replacements) {
String[] result = new String[] { string };
while (placeholders.hasNext()) {
result = multiply(result, (String) placeholders.next(), (String[]) replacements.next());
}
return result;
}
/**
* 把数组中的所有元素出现的字符串进行替换,把旧字符串替换为新字符数组的所有元素,只替换第一次出现的字符。
*
* @param strings
* 需要替换的数组
* @param placeholder
* 需要替换的字符串
* @param replacements
* 新字符串数组
* @return 替换后的字符串数组
*/
private static String[] multiply(String[] strings, String placeholder, String[] replacements) {
String[] results = new String[replacements.length * strings.length];
int n = 0;
for (int i = 0; i < replacements.length; i++) {
for (int j = 0; j < strings.length; j++) {
results[n++] = replaceOnce(strings[j], placeholder, replacements[i]);
}
}
return results;
}
/**
* 统计Char在字符串中出现在次数,如"s"在字符串"string"中出现的次数
*
* @param string
* 字符串
* @param character
* 需要进行统计的char
* @return 数量
*/
public static int count(String string, char character) {
int n = 0;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == character) {
n++;
}
}
return n;
}
/**
* 描述:计算字符串中未引用的字符
*
* @param string
* 字符串
* @param character
* 字符
* @return 未引用的字符数
*/
public static int countUnquoted(String string, char character) {
if (SINGLE_QUOTE == character) {
throw new IllegalArgumentException("Unquoted count of quotes is invalid");
}
int count = 0;
int stringLength = string == null ? 0 : string.length();
boolean inQuote = false;
for (int indx = 0; indx < stringLength; indx++) {
if (inQuote) {
if (SINGLE_QUOTE == string.charAt(indx)) {
inQuote = false;
}
} else if (SINGLE_QUOTE == string.charAt(indx)) {
inQuote = true;
} else if (string.charAt(indx) == character) {
count++;
}
}
return count;
}
/**
*
* 描述:描述:判断字符串是否为空,如果为true则为空。与isEmpty不同,如果字符为" "也视为空字符
*
* @param str
* 字符串
* @return
*/
public static boolean isBlank(String str) {
boolean b = true;// 20140507 modify by liwei 修复对" "为false的bug
if (str == null) {
b = true;
} else {
int strLen = str.length();
if (strLen == 0) {
b = true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
b = false;
break;
}
}
}
return b;
}
/**
*
* 描述:描述:判断字符串是否为空,如果为true则不为空。与isNotEmpty不同,如果字符为" "也视为空字符
*
* @param str
* 字符串
* @return
*/
public static boolean isNotBlank(String str) {
int strLen = 0;
if (str != null)
strLen = str.length();
if (str == null || strLen == 0) {
return false;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
/**
* 判断字符串是否非空,如果为true则不为空
*
* @param string
* 字符串
* @return true/false
*/
public static boolean isNotEmpty(String string) {
return string != null && string.length() > 0;
}
/**
* 判断字符串是否空,如果为true则为空
*
* @param str
* 字符串
* @return true/false
*/
public static boolean isEmpty(String str) {
if (str == null || str.trim().length() == 0) {
return true;
}
return false;
}
/**
* 向字符串添加上前缀,并以.作为分隔符
*
* @param name
* 需要添加前缀的字符串
* @param prefix
* 前缀
* @return 添加前缀后的字符串
*/
public static String qualify(String name, String prefix) {
if (name.startsWith("'")) {
return name;
}
return new StringBuffer(prefix.length() + name.length() + 1).append(prefix).append(DOT).append(name).toString();
}
/**
* 向字符串数组中的所有字符添加上前缀,前以点作为分隔符
*
* @param names
* 字符串数组
* @param prefix
* 前缀
* @return 添加前缀后的字符串数组
*/
public static String[] qualify(String[] names, String prefix) {
if (prefix == null) {
return names;
}
int len = names.length;
String[] qualified = new String[len];
for (int i = 0; i < len; i++) {
qualified[i] = qualify(prefix, names[i]);
}
return qualified;
}
/**
* 在字符串中,查找字符第一次出现的位置
*
* @param sqlString
* 原字符串
* @param string
* 需要查找到字符串
* @param startindex
* 开始位置
* @return 第一个出现的位置
*/
public static int firstIndexOfChar(String sqlString, String string, int startindex) {
int matchAt = -1;
for (int i = 0; i < string.length(); i++) {
int curMatch = sqlString.indexOf(string.charAt(i), startindex);
if (curMatch >= 0) {
if (matchAt == -1) {
matchAt = curMatch;
} else {
matchAt = Math.min(matchAt, curMatch);
}
}
}
return matchAt;
}
/**
* 从字符串中提取指字长度的字符。区分中英文。<br>
* 如果需要加省略号,则将在指定长度上少取3个字符宽度,末尾加上"......"。
*
* @param string
* 字符串
* @param length
* 要取的字符长度,此为中文长度,英文仅当作半个字符。
* @param appendSuspensionPoints
* 是否需要加省略号
* @return 提取后的字符串
*/
public static String truncate(String string, int length, boolean appendSuspensionPoints) {
if (isEmpty(string) || length < 0) {
return string;
}
if (length == 0) {
return "";
}
int strLength = string.length(); // 字符串字符个数
int byteLength = byteLength(string); // 字符串字节长度
length *= 2; // 换成字节长度
// 判断是否需要加省略号
boolean needSus = false;
if (appendSuspensionPoints && byteLength >= length) {
needSus = true;
// 如果需要加省略号,则要少取2个字节用来加省略号
length -= 2;
}
StringBuffer result = new StringBuffer();
int count = 0;
for (int i = 0; i < strLength; i++) {
if (count >= length) { // 取完了
break;
}
char c = string.charAt(i);
if (isLetter(c)) { // Ascill字符
result.append(c);
count += 1;
} else { // 非Ascill字符
if (count == length - 1) { // 如果只要取1个字节了,而后面1个是汉字,就放空格
result.append(" ");
count += 1;
} else {
result.append(c);
count += 2;
}
}
}
if (needSus) {
result.append("...");
}
return result.toString();
}
/**
* 描述:判断一个字符是Ascill字符还是其它字符(如汉,日,韩文字符)
*
* @param c
* 需要判断的字符
* @return
*/
public static boolean isLetter(char c) {
int k = HEX_80;
return c / k == 0 ? true : false;
}
/**
* 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1
*
* @param s
* ,需要得到长度的字符串
* @return int, 得到的字符串长度
*/
public static int byteLength(String s) {
char[] c = s.toCharArray();
int len = 0;
for (int i = 0; i < c.length; i++) {
if (isLetter(c[i])) {
len++;
} else {
len += 2;
}
}
return len;
}
/**
* 从字符串中提取指字长度的字符
*
* @param string
* 字符串
* @param length
* 字符长度
* @return 提取后的字符串
*/
public static String truncate(String string, int length) {
if (isEmpty(string)) {
return string;
}
if (string.length() <= length) {
return string;
} else {
return string.substring(0, length);
}
}
/**
* 去丢字符的左侧空格
*
* @param value
* 字符串
* @return 去丢左侧空格后的字符串
*/
public static String leftTrim(String value) {
String result = value;
if (result == null) {
return result;
}
char ch[] = result.toCharArray();
int index = -1;
for (int i = 0; i < ch.length; i++) {
if (!Character.isWhitespace(ch[i])) {
break;
}
index = i;
}
if (index != -1) {
result = result.substring(index + 1);
}
return result;
}
/**
* 去丢字符的右侧空格
*
* @param value
* 字符串
* @return 去右侧空格后的字符串
*/
public static String rightTrim(String value) {
String result = value;
if (result == null) {
return result;
}
char ch[] = result.toCharArray();
int endIndex = -1;
for (int i = ch.length - 1; i > -1; i--) {
if (!Character.isWhitespace(ch[i])) {
break;
}
endIndex = i;
}
if (endIndex != -1) {
result = result.substring(0, endIndex);
}
return result;
}
/**
* 把null字符串转化为""
*
* @param source
* 空字符串
* @return 转化后的字符串
*/
public static String n2s(String source) {
return source != null ? source : "";
}
/**
* 如果字符串为空,则返回默认字符串
*
* @param source
* 源字符串
* @param defaultStr
* 默认字符串
* @return 转换后的字符串
*/
public static String n2s(String source, String defaultStr) {
return source != null ? source : defaultStr;
}
/**
* 将字符串格式化成 HTML 以SCRIPT变量 主要是替换单,双引号,以将内容格式化输出,适合于 HTML 中的显示输出
*
* @param str
* 要格式化的字符串
* @return 格式化后的字符串
*/
public static String toScript(String str) {
if (str == null) {
return null;
}
String html = new String(str);
html = replace(html, "\"", "\\\"");
html = replace(html, "\r\n", "\n");
html = replace(html, "\n", "\\n");
html = replace(html, "\t", " ");
html = replace(html, "\'", "\\\'");
html = replace(html, " ", " &nbsp;");
html = replace(html, "</script>", "<\\/script>");
html = replace(html, "</SCRIPT>", "<\\/SCRIPT>");
return html;
}
/**
* 同于String#trim(),但是检测null,如果原字符串为null,则仍然返回null
*
* @param s
* s
* @return
*/
public static String trim(String s) {
return s == null ? s : s.trim();
}
/**
* 对字符串进行空格处理,如果字符串为null呀是空字符串, 则返回默认的数字。
*
* @param source
* 需要进行处理的字符串
* @param defaultValue
* 缺省值
* @return 字符串的数字值
*/
public static int strTrim(String source, int defaultValue) {
if (isEmpty(source)) {
return defaultValue;
}
try {
source = source.trim();
int value = (new Integer(source)).intValue();
return value;
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("数字转换出错,请检查数据来源。返回默认值");
return defaultValue;
}
}
/**
* 对字符串进行过滤处理,如果字符串是null或为空字符串, 返回默认值。
*
* @param source
* 需要进行处理的字符串
* @param defaultValue
* 缺省值
* @return 过滤后的字符串
*/
public static String strTrim(String source, String defaultValue) {
if (StringHelper.isEmpty(source)) {
return defaultValue;
}
try {
source = source.trim();
return source;
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("字符串去空格失败,返回默认值");
return defaultValue;
}
}
/**
* 描述:为了防止跨站脚本攻击,转换<>这种尖括号。
*
* @param source
* @return
*/
public static String encodeURL(String source) {
if (source == null) {
return null;
}
String html = new String(source);
html = replace(html, "<", "&lt;");
html = replace(html, ">", "&gt;");
html = replace(html, "\"", "&quot;");
html = replace(html, " ", "&nbsp;");
html = replace(html, "\'", "&acute;");
html = replace(html, "\\", "&#092;");
html = replace(html, "&", "&amp;");
html = replace(html, "\r", "");
html = replace(html, "\n", "");
html = replace(html, "(", "&#40;");
html = replace(html, ")", "&#41;");
html = replace(html, "[", "&#91;");
html = replace(html, "]", "&#93;");
html = replace(html, ";", "&#59;");
html = replace(html, "/", "&#47;");
return html;
}
/**
* 把字符串中一些特定的字符转换成html字符,如&、<、>、"号等
*
* @param source
* 需要进行处理的字符串
* @return 处理后的字符串
*/
public static String encodeHtml(String source) {
if (source == null) {
return null;
}
String html = new String(source);
html = replace(html, "&", "&amp;");
html = replace(html, "<", "&lt;");
html = replace(html, ">", "&gt;");
html = replace(html, "\"", "&quot;");
html = replace(html, " ", "&nbsp;");
html = replace(html, "\'", "&acute;");
return html;
}
/**
* 把一些html的字符串还原
*
* @param source
* 需要进行处理的字符串
* @return 处理后的字符串
*/
public static String decodeHtml(String source) {
if (source == null) {
return null;
}
String html = new String(source);
html = replace(html, "&amp;", "&");
html = replace(html, "&lt;", "<");
html = replace(html, "&gt;", ">");
html = replace(html, "&quot;", "\"");
html = replace(html, " ", "&nbsp;");
html = replace(html, "\r\n", "\n");
html = replace(html, "\n", "<br>\n");
html = replace(html, "\t", " ");
html = replace(html, " ", " &nbsp;");
return html;
}
/**
* 判断字符串是否为布尔值,如true/false等
*
* @param source
* 需要进行判断的字符串
* @return 返回字符串的布尔值
*/
public static boolean isBoolean(String source) {
if (source.equalsIgnoreCase("true") || source.equalsIgnoreCase("false")) {
return true;
}
return false;
}
/**
* 去除字符串中的最后字符
*
* @param str
* 原字符串
* @param strMove
* 要去除字符 比如","
* @return 去除后的字符串
*/
public static String lastCharTrim(String str, String strMove) {
if (isEmpty(str)) {
return "";
}
String newStr = "";
if (str.lastIndexOf(strMove) != -1 && str.lastIndexOf(strMove) == str.length() - 1) {
newStr = str.substring(0, str.lastIndexOf(strMove));
}
return newStr;
}
/**
* 清除字符串里的html代码
*
* @param html
* 需要进行处理的字符串
* @return 清除html后的代码
*/
public static String clearHtml(String html) {
if (isEmpty(html)) {
return "";
}
String patternStr = "(<[^>]*>)";
Pattern pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
Matcher matcher = null;
StringBuffer bf = new StringBuffer();
try {
matcher = pattern.matcher(html);
boolean first = true;
int start = 0;
int end = 0;
while (matcher.find()) {
start = matcher.start(1);
if (first) {
bf.append(html.substring(0, start));
first = false;
} else {
bf.append(html.substring(end, start));
}
end = matcher.end(1);
}
if (end < html.length()) {
bf.append(html.substring(end));
}
html = bf.toString();
return html;
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("清除html标签失败");
} finally {
pattern = null;
matcher = null;
}
return html;
}
/**
* 把文杯格式转换为html格式
*
* @param content
* 转换的内容
* @return
*/
public static String textFmtToHtmlFmt(String content) {
content = StringHelper.replace(content, " ", "&nbsp;");
content = StringHelper.replace(content, "\r\n", "<br>");
content = StringHelper.replace(content, "\n", "<br>");
return content;
}
/**
*
* 描述:大写英文字母转换成小写
*
* @param strIn
* 字符串参数
* @return
*/
public static String toLowerStr(String strIn) {
String strOut = new String(); // 输出的字串
int len = strIn.length(); // 参数的长度
int i = 0; // 计数器
char ch; // 存放参数的字符
while (i < len) {
ch = strIn.charAt(i);
if (ch >= 'A' && ch <= 'Z') {
ch = (char) (ch - 'A' + 'a');
}
strOut += ch;
i++;
}
return strOut;
}
/**
*
* 描述:小写英文字母转换成大写
*
* @param strIn
* 字符串参数
* @return
*/
public static String toUpperStr(String strIn) {
String strOut = new String(); // 输出的字串
int len = strIn.length(); // 参数的长度
int i = 0; // 计数器
char ch; // 存放参数的字符
while (i < len) {
ch = strIn.charAt(i);
if (ch >= 'a' && ch <= 'z') {
ch = (char) (ch - 'a' + 'A');
}
strOut += ch;
i++;
}
return strOut;
}
/**
* 货币缩写,提供亿和万两个单位,并精确到小数点2位 切换到新的算法:对数算法
*
* @param original
* @return
*/
public static String currencyShortFor(String original) {
if (StringHelper.isBlank(original)) {
return "";
} else {
String shortFor = "";
double shortForValue = 0;
DecimalFormat df = new DecimalFormat("#.00");
try {
double account = Double.parseDouble(original);
if (account / 100000000 > 1) {
shortForValue = account / 100000000;
shortFor = df.format(shortForValue) + "亿";
} else if (account / 10000 > 1) {
shortForValue = account / 10000;
shortFor = df.format(shortForValue) + "万";
} else {
shortFor = original;
}
} catch (NumberFormatException e) {
e.printStackTrace();
System.err.println("字符串[" + original + "]转换成数字出错");
}
return shortFor;
}
}
/**
* 将日期格式由yyyyMMdd装换为yyyy-MM-dd
*
* @param date
* Date string whose format is yyyyMMdd.
* @return
*/
public static String formatDate(String date) {
if (isBlank(date) || date.length() < 8) {
return "";
}
StringBuffer dateBuf = new StringBuffer();
dateBuf.append(date.substring(0, 4));
dateBuf.append("-");
dateBuf.append(date.substring(4, 6));
dateBuf.append("-");
dateBuf.append(date.substring(6, 8));
return dateBuf.toString();
}
/**
* 判断是否为整数
*
* @param str
* 传入的字符串
* @return 是整数返回true,否则返回false
*/
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^\\d+(\\.0)?$", Pattern.CASE_INSENSITIVE);
return pattern.matcher(str).matches();
}
/**
* 用于=中英文混排标题中限定字符串长度。保证显示长度最多只相差一个全角字符。
*
* @param string
* 需要截取的字符串
* @param byteCount
* 字节数(度量标准为中文为两个字节,ASCII字符为一个字节,这样子,刚好匹配ASCII为半角字符,而中文为全角字符,
* 保证在网页上中英文混合的句子长度一致)
* @return
* @throws UnsupportedEncodingException
*/
public static String substring(String string, int byteCount) throws UnsupportedEncodingException {
if (isBlank(string)) {
return string;
}
byte[] bytes = string.getBytes("Unicode");// 使用UCS-2编码.
int viewBytes = 0; // 表示当前的字节数(英文为单字节,中文为双字节的表示方法)
int ucs2Bytes = 2; // 要截取的字节数,从第3个字节开始,前两位为位序。(UCS-2的表示方法)
// UCS-2每个字符使用两个字节来编码。
// ASCII n+=1,i+=2
// 中文 n+=2,i+=2
for (; ucs2Bytes < bytes.length && viewBytes < byteCount; ucs2Bytes++) {
// 奇数位置,如3、5、7等,为UCS2编码中两个字节的第二个字节
if (ucs2Bytes % 2 == 1) {
viewBytes++; // 低字节,无论中英文,都算一个字节。
} else {
// 当UCS2编码的第一个字节不等于0时,该UCS2字符为汉字,一个汉字算两个字节
// 高位时,仅中文的高位算一字节。
if (bytes[ucs2Bytes] != 0) {
viewBytes++;
}
}
}
// 截一半的汉字要保留
if (ucs2Bytes % 2 == 1) {
ucs2Bytes = ucs2Bytes + 1;
}
String result = new String(bytes, 0, ucs2Bytes, "Unicode");// 将字节流转换为java默认编码UTF-8的字符串
if (bytes.length > ucs2Bytes) {
result += "...";
}
return result;
}
/**
* 描述:根据长度截断字串
*
* @param str
* 字串
* @param length
* 截取长度
* @return
*/
public static String[] splite(String str, int length) {
if (StringHelper.isEmpty(str)) {
return null;
}
String[] strArr = new String[(str.length() + length - 1) / length];
for (int i = 0; i < strArr.length; i++) {
if (str.length() > i * length + length - 1) {
strArr[i] = str.substring(i * length, i * length + length - 1);
} else {
strArr[i] = str.substring(i * length);
}
}
return strArr;
}
/**
* 描述:把某一个字符变成大写
*
* @param str
* str 字串
* @param index
* 第几个字符
* @return
*/
public static String toUpOneChar(String str, int index) {
return toUpOrLowOneChar(str, index, 1);
}
/**
* 描述:把某一个字符变成小写 作者:李建 时间:Dec 17, 2010 9:42:32 PM
*
* @param str
* str 字串
* @param index
* 第几个字符
* @return
*/
public static String toLowOneChar(String str, int index) {
return toUpOrLowOneChar(str, index, 0);
}
/**
* 描述:把某一个字符变成大写或小写 作者:李建 时间:Dec 17, 2010 9:39:32 PM
*
* @param str
* 字串
* @param index
* 第几个字符
* @param upOrLow
* 大小写 1:大写;0小写
* @return
*/
public static String toUpOrLowOneChar(String str, int index, int upOrLow) {
if (StringHelper.isNotEmpty(str) && index > -1 && index < str.length()) {
char[] chars = str.toCharArray();
if (upOrLow == 1) {
chars[index] = Character.toUpperCase(chars[index]);
} else {
chars[index] = Character.toLowerCase(chars[index]);
}
return new String(chars);
}
return str;
}
/**
* 将字符串用分隔符断裂成字符串列表
*
* @param value
* 原字符串
* @param separator
* 分隔字符
* @return 结果列表
*/
public static List<String> split2List(String value, String separator) {
List<String> ls = new ArrayList<String>();
int i = 0, j = 0;
while ((i = value.indexOf(separator, i)) != -1) {
ls.add(value.substring(j, i));
++i;
j = i;
}
ls.add(value.substring(j));
return ls;
}
/**
* 将数组用分隔符连接成新字符串(split的逆方法)
*
* @param strs
* 字符串数组
* @param sep
* 分隔符
* @return 结果字符串
*/
public static String join(String[] strs, String sep) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < strs.length; i++) {
res.append(strs[i] + sep);
}
return res.substring(0, res.length() - sep.length());
}
/**
* 获得一个UUID
*
* @return String UUID
*/
public static String getUUID() {
String str = UUID.randomUUID().toString();// 标准的UUID格式为:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx(8-4-4-4-12)
// 去掉"-"符号,不用replaceAll的原因与split一样,replaceAll支持正则表达式,频繁使用时效率不够高(当然偶尔用一下影响也不会特别严重)
return join(split(str, "-"), "");
}
/**
* <pre>
* 例: String strVal="This is a dog"; String
* strResult=CTools.replace(strVal,"dog","cat"); 结果: strResult equals
* "This is cat"
*
* @param strSrc
* 要进行替换操作的字符串
* @param strOld
* 要查找的字符串
* @param strNew
* 要替换的字符串
* @return 替换后的字符串
*
* <pre>
*/
public static final String replaceAllStr(String strSrc, String strOld, String strNew) {
if (strSrc == null || strOld == null || strNew == null)
return "";
int i = 0;
if (strOld.equals(strNew)) // 避免新旧字符一样产生死循环
return strSrc;
if ((i = strSrc.indexOf(strOld, i)) >= 0) {
char[] arr_cSrc = strSrc.toCharArray();
char[] arr_cNew = strNew.toCharArray();
int intOldLen = strOld.length();
StringBuffer buf = new StringBuffer(arr_cSrc.length);
buf.append(arr_cSrc, 0, i).append(arr_cNew);
i += intOldLen;
int j = i;
while ((i = strSrc.indexOf(strOld, i)) > 0) {
buf.append(arr_cSrc, j, i - j).append(arr_cNew);
i += intOldLen;
j = i;
}
buf.append(arr_cSrc, j, arr_cSrc.length - j);
return buf.toString();
}
return strSrc;
}
/**
* 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串 可对表单数据据进行处理对一些页面特殊字符进行处理如'
* <','>','"',''','&'
*
* @param strSrc
* 要进行替换操作的字符串
* @return 替换特殊字符后的字符串
* @since 1.0
*/
public static String htmlEncode(String strSrc) {
if (strSrc == null)
return "";
char[] arr_cSrc = strSrc.toCharArray();
StringBuffer buf = new StringBuffer(arr_cSrc.length);
char ch;
for (int i = 0; i < arr_cSrc.length; i++) {
ch = arr_cSrc[i];
if (ch == '<')
buf.append("&lt;");
else if (ch == '>')
buf.append("&gt;");
else if (ch == '"')
buf.append("&quot;");
else if (ch == '\'')
buf.append("&#039;");
else if (ch == '&')
buf.append("&amp;");
else
buf.append(ch);
}
return buf.toString();
}
/**
* 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串 可对表单数据据进行处理对一些页面特殊字符进行处理如'
* <','>','"',''','&'
*
* @param strSrc
* 要进行替换操作的字符串
* @param quotes
* 为0时单引号和双引号都替换,为1时不替换单引号,为2时不替换双引号,为3时单引号和双引号都不替换
* @return 替换特殊字符后的字符串
* @since 1.0
*/
public static String htmlEncode(String strSrc, int quotes) {
if (strSrc == null)
return "";
if (quotes == 0) {
return htmlEncode(strSrc);
}
char[] arr_cSrc = strSrc.toCharArray();
StringBuffer buf = new StringBuffer(arr_cSrc.length);
char ch;
for (int i = 0; i < arr_cSrc.length; i++) {
ch = arr_cSrc[i];
if (ch == '<')
buf.append("&lt;");
else if (ch == '>')
buf.append("&gt;");
else if (ch == '"' && quotes == 1)
buf.append("&quot;");
else if (ch == '\'' && quotes == 2)
buf.append("&#039;");
else if (ch == '&')
buf.append("&amp;");
else
buf.append(ch);
}
return buf.toString();
}
/**
* 和htmlEncode正好相反
*
* @param strSrc
* 要进行转换的字符串
* @return 转换后的字符串
* @since 1.0
*/
public static String htmlDecode(String strSrc) {
if (strSrc == null)
return "";
strSrc = strSrc.replaceAll("&lt;", "<");
strSrc = strSrc.replaceAll("&gt;", ">");
strSrc = strSrc.replaceAll("&quot;", "\"");
strSrc = strSrc.replaceAll("&#039;", "'");
strSrc = strSrc.replaceAll("&amp;", "&");
return strSrc;
}
/**
* 实际处理 return toChineseNoReplace(null2Blank(str));
*
* @param str
* 要进行处理的字符串
* @return 转换后的字符串
* @see fs_com.utils.CTools#toChinese
* @see fs_com.utils.CTools#null2Blank
*/
public static String toChineseAndHtmlEncode(String str, int quotes) {
try {
if (str == null) {
return "";
} else {
str = str.trim();
str = new String(str.getBytes("ISO8859_1"), "GBK");
String htmlEncode = htmlEncode(str, quotes);
return htmlEncode;
}
} catch (Exception exp) {
return "";
}
}
/**
* 把null值和""值转换成&nbsp; 主要应用于页面表格格的显示
*
* @param str
* 要进行处理的字符串
* @return 转换后的字符串
*/
public static String str4Table(String str) {
if (str == null)
return "&nbsp;";
else if (str.equals(""))
return "&nbsp;";
else
return str;
}
}
package com.platform.utils.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串相关方法
*
*/
public class StringUtil {
/**
* 将以逗号分隔的字符串转换成字符串数组
* @param valStr
* @return String[]
*/
public static String[] StrList(String valStr){
int i = 0;
String TempStr = valStr;
String[] returnStr = new String[valStr.length() + 1 - TempStr.replace(",", "").length()];
valStr = valStr + ",";
while (valStr.indexOf(',') > 0)
{
returnStr[i] = valStr.substring(0, valStr.indexOf(','));
valStr = valStr.substring(valStr.indexOf(',')+1 , valStr.length());
i++;
}
return returnStr;
}
/**获取字符串编码
* @param str
* @return
*/
public static String getEncoding(String str) {
String encode = "GB2312";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s = encode;
return s;
}
} catch (Exception exception) {
}
encode = "ISO-8859-1";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s1 = encode;
return s1;
}
} catch (Exception exception1) {
}
encode = "UTF-8";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s2 = encode;
return s2;
}
} catch (Exception exception2) {
}
encode = "GBK";
try {
if (str.equals(new String(str.getBytes(encode), encode))) {
String s3 = encode;
return s3;
}
} catch (Exception exception3) {
}
return "";
}
/**
*
* 数组去空
* ysl
*/
public static String[] getArray(String[] strArray) {
List<String> strList= Arrays.asList(strArray);
List<String> strListNew=new ArrayList<>();
for (int i = 0; i <strList.size(); i++) {
if (strList.get(i)!=null&&!strList.get(i).equals("")){
strListNew.add(strList.get(i));
}
}
String[] strNewArray = strListNew.toArray(new String[strListNew.size()]);
return strNewArray;
}
/**
* 获取所有img标签
*
* @param htmlStr
* @return
*/
public static List<String> getImgStr(String htmlStr) {
List<String> pics = new ArrayList();
String img = "";
Pattern p_image;
Matcher m_image;
// String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
m_image = p_image.matcher(htmlStr);
while (m_image.find()) {
// 得到<img />数据
img = m_image.group();
// 匹配<img>中的src数据
Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
while (m.find()) {
pics.add(m.group(1));
}
}
return pics;
}
/**
* 数组去重
* @param t1
* @param t2
* @return
*/
public static <T> List<T> compare(T[] t1, T[] t2) {
List<T> list1 = Arrays.asList(t1);
List<T> list2 = new ArrayList<T>();
for (T t : t2) {
if (!list1.contains(t)) {
list2.add(t);
}
}
return list2;
}
/**
* 获取生成字母+数字
* @param length 生成的随机字符串长度
* */
public static String getRandomCode(int length){
String randomcode = "";
// 用字符数组的方式随机
String model = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";
char[] m = model.toCharArray();
for (int j = 0; j < length; j++) {
char c = m[(int) (Math.random() * 36)];
// 保证六位随机数之间没有重复的
if (randomcode.contains(String.valueOf(c))) {
j--;
continue;
}
randomcode = randomcode + c;
}
System.out.println(randomcode);
return randomcode;
}
/**
* 获取数字
* @param length 生成的随机字符串长度
* */
public static String getRandomNumber(int length){
String base = "0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
}
package com.platform.utils.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 说明:常用工具
* @version
*/
public class Tools {
/**
* 随机生成六位数验证码
* @return
*/
public static int getRandomNum(){
Random r = new Random();
return r.nextInt(900000)+100000;//(Math.random()*(999999-100000)+100000)
}
/**
* 检测字符串是否不为空(null,"","null")
* @param s
* @return 不为空则返回true,否则返回false
*/
public static boolean notEmpty(String s){
return s!=null && !"".equals(s) && !"null".equals(s);
}
/**
* 检测字符串是否为空(null,"","null")
* @param s
* @return 为空则返回true,不否则返回false
*/
public static boolean isEmpty(String s){
return s==null || "".equals(s) || "null".equals(s);
}
/**
* 字符串转换为字符串数组
* @param str 字符串
* @param splitRegex 分隔符
* @return
*/
public static String[] str2StrArray(String str,String splitRegex){
if(isEmpty(str)){
return null;
}
return str.split(splitRegex);
}
/**
* 用默认的分隔符(,)将字符串转换为字符串数组
* @param str 字符串
* @return
*/
public static String[] str2StrArray(String str){
return str2StrArray(str,",\\s*");
}
/**
* 按照yyyy-MM-dd HH:mm:ss的格式,日期转字符串
* @param date
* @return yyyy-MM-dd HH:mm:ss
*/
public static String date2Str(Date date){
return date2Str(date,"yyyy-MM-dd HH:mm:ss");
}
/**
* 按照yyyy-MM-dd HH:mm:ss的格式,字符串转日期
* @param date
* @return
*/
public static Date str2Date(String date){
if(notEmpty(date)){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return sdf.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return new Date();
}else{
return null;
}
}
/**
* 按照参数format的格式,日期转字符串
* @param date
* @param format
* @return
*/
public static String date2Str(Date date,String format){
if(date!=null){
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}else{
return "";
}
}
/**
* 把时间根据时、分、秒转换为时间段
* @param StrDate
*/
public static String getTimes(String StrDate){
String resultTimes = "";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now;
try {
now = new Date();
Date date=df.parse(StrDate);
long times = now.getTime()-date.getTime();
long day = times/(24*60*60*1000);
long hour = (times/(60*60*1000)-day*24);
long min = ((times/(60*1000))-day*24*60-hour*60);
long sec = (times/1000-day*24*60*60-hour*60*60-min*60);
StringBuffer sb = new StringBuffer();
//sb.append("发表于:");
if(hour>0 ){
sb.append(hour+"小时前");
} else if(min>0){
sb.append(min+"分钟前");
} else{
sb.append(sec+"秒前");
}
resultTimes = sb.toString();
} catch (ParseException e) {
e.printStackTrace();
}
return resultTimes;
}
/**
* 写txt里的单行内容
* @param filePath 文件路径
* @param content 写入的内容
*/
public static void writeFile(String fileP,String content){
String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../"; //项目路径
filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
if(filePath.indexOf(":") != 1){
filePath = File.separator + filePath;
}
try {
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath),"utf-8");
BufferedWriter writer=new BufferedWriter(write);
writer.write(content);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 验证邮箱
* @param email
* @return
*/
public static boolean checkEmail(String email){
boolean flag = false;
try{
String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(email);
flag = matcher.matches();
}catch(Exception e){
flag = false;
}
return flag;
}
/**
* 验证手机号码
* @param mobiles
* @return
*/
public static boolean checkMobileNumber(String mobileNumber){
boolean flag = false;
try{
Pattern regex = Pattern.compile("^(((13[0-9])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8})|(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})$");
Matcher matcher = regex.matcher(mobileNumber);
flag = matcher.matches();
}catch(Exception e){
flag = false;
}
return flag;
}
/**
* 检测KEY是否正确
* @param paraname 传入参数
* @param FKEY 接收的 KEY
* @return 为空则返回true,不否则返回false
*/
public static boolean checkKey(String paraname, String FKEY){
paraname = (null == paraname)? "":paraname;
return MD5.md5(paraname+DateUtil.getDays()+",fh,").equals(FKEY);
}
/**
* 读取txt里的单行内容
* @param filePath 文件路径
*/
public static String readTxtFile(String fileP) {
try {
String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""))+"../../"; //项目路径
filePath = filePath.replaceAll("file:/", "");
filePath = filePath.replaceAll("%20", " ");
filePath = filePath.trim() + fileP.trim();
if(filePath.indexOf(":") != 1){
filePath = File.separator + filePath;
}
String encoding = "utf-8";
File file = new File(filePath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file), encoding); // 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
return lineTxt;
}
read.close();
}else{
System.out.println("找不到指定的文件,查看此路径是否正确:"+filePath);
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
}
return "";
}
public static final String generateGUID()
{
UUID uuid=UUID.randomUUID();
return uuid.toString().replaceAll("-", "");
}
public static void main(String[] args) {
System.out.println(generateGUID());
}
}
package com.platform.utils.util;
import java.util.UUID;
public class UuidUtil {
public static String get32UUID() {
String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
return uuid;
}
public static void main(String[] args) {
System.out.println(get32UUID());
}
}
package com.platform.utils.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
public class kuaidi100Util {
private final static String customer = "5A98636B1BD6C6B20EF6EF35743C1468";
private final static String key = "ILFQRhLY8583";
private static MessageDigest _mdInst = null;
private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private static MessageDigest getMdInst() {
if (_mdInst == null) {
try {
_mdInst = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return _mdInst;
}
public static String encode(String s) {
try {
byte[] btInput = s.getBytes();
// 使用指定的字节更新摘要
getMdInst().update(btInput);
// 获得密文
byte[] md = getMdInst().digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 查询快递物流信息
* @param com 快递公司的代码
* @param num 快递单号
* @return
*/
public static String querykuaidi(String com,String num) {
String param ="{\"com\":\""+com+"\",\"num\":\""+num+"\"}";
String sign = kuaidi100Util.encode(param+key+customer);
HashMap params = new HashMap();
params.put("param",param);
params.put("sign",sign);
params.put("customer",customer);
String resp = null;
try {
resp = HttpUtils.sendPost("http://poll.kuaidi100.com/poll/query.do", params).toString();
System.out.println(resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resp;
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论