Commit c3d62b18 authored by 吴琼's avatar 吴琼

交易凭证

parent 0a28b76a
...@@ -253,7 +253,26 @@ ...@@ -253,7 +253,26 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.6</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.1</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
package cn.quantgroup.customer.entity;
import lombok.*;
import javax.persistence.*;
@Entity
@Table(name = "transaction_receipt_record")
@ToString
@Builder
@Getter
@Setter
@AllArgsConstructor
public class TransactionReceiptRecord {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id")
private Integer userId;
@Column(name = "user_name")
private String userName;
@Column(name = "serial_no")
private String serialNo;
@Column(name = "import_status")
private Integer importStatus;
@Column(name = "export_status")
private Integer exportStatus;
@Column(name = "order_no")
private String orderNo;
@Column(name = "batch_no")
private Long batchNo;
@Column(name = "sign_status")
private Long signStatus;
@Column(name = "pdf_status")
private Long pdfStatus;
public TransactionReceiptRecord() {
}
}
package cn.quantgroup.customer.repo;
import cn.quantgroup.customer.entity.TransactionReceiptRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import javax.transaction.Transactional;
import java.util.List;
public interface TransactionReceiptRecordRepo extends JpaRepository<TransactionReceiptRecord, Long>, JpaSpecificationExecutor<TransactionReceiptRecord> {
@Query(value = "select max(batch_no) from transaction_receipt_record where export_status =?1 ", nativeQuery = true)
Long findMaxbatchNo(Integer status);
@Query(value = "select count(1) from transaction_receipt_record where user_id =?1 and user_name =?2 and order_no =?3 ", nativeQuery = true)
Long selectCountByUserIdAndOrderNo(Integer userId,String userName,String orderNo);
@Query(value = "select * from transaction_receipt_record where import_status = ?1 ", nativeQuery = true)
List<TransactionReceiptRecord> selectRecordsByImportStatus(Integer status);
@Query(value = "select count(1) from transaction_receipt_record where import_status =?1 ", nativeQuery = true)
Long selectCountByImportStatus(Integer status);
@Modifying
@Transactional
@Query(value = "update transaction_receipt_record set import_status = ?1 where order_no =?2 ", nativeQuery = true)
Long updateTransactionStatusByImportStatus(Integer status,String orderNo);
@Modifying
@Transactional
@Query(value = "update transaction_receipt_record set sign_status = ?1 where order_no =?2 ", nativeQuery = true)
Long updatePDFStatusByOrderNo(Integer status,String orderNo);
}
package cn.quantgroup.customer.rest;
import cn.quantgroup.customer.rest.param.transactionreceipt.TransactionReceiptRecordQuery;
import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.rest.vo.transaction.*;
import cn.quantgroup.customer.service.ITransactionReceiptRecordService;
import cn.quantgroup.customer.service.http.IHttpService;
import cn.quantgroup.customer.util.FileToZip;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Slf4j
@RestController
@RequestMapping("/transactionReceiptRecord")
public class TransactionReceiptRecordRest {
@Autowired
private ITransactionReceiptRecordService transactionReceiptRecordService;
@Autowired
private IHttpService httpService;
/**
* 根据筛选条件进行查询
* @param query
* @return
*/
@RequestMapping("/orderQuery/query_page")
public JsonResult queryPage(@RequestBody TransactionReceiptRecordQuery query) {
if (query.getPageNo()== null || query.getPageNo() < 1) {
log.error("[TransactionReceiptRecordRest_queryPage]查询参数pageNumber错误,pageNo={}", query.getPageNo());
return JsonResult.buildErrorStateResult("查询参数pageNo错误");
}
Integer pageNo = query.getPageNo() - 1;
query.setPageNo(pageNo);
if (query.getPageSize() == null) {
log.error("[workOrderRest_queryPage]查询参数pageSize错误,pageSize={}", query.getPageSize());
return JsonResult.buildErrorStateResult("查询参数pageSize错误");
}
return transactionReceiptRecordService.findRecordsByQuery(query);
}
/**
* 导入excel表格
*/
@RequestMapping("/orderQuery/importTransactionReceiptRecord")
public JsonResult importTransactionReceiptRecord(MultipartFile file) {
try{
return transactionReceiptRecordService.importTransactionReceiptRecord(file);
}catch(IOException e){
e.printStackTrace();
return JsonResult.buildErrorStateResult("上传文件出现错误");
}
}
/**
* 导出压缩包之前先校验
*/
@RequestMapping("/orderQuery/checkCanExport")
public JsonResult checkCanExport() {
return transactionReceiptRecordService.checkCanExport();
}
@RequestMapping("/test")
public JsonResult test() {
String userIds="70356056,70356055";
String url ="http://passportapi-qa2.liangkebang.net/api/sync/listByUserIds";
Map param = Maps.newHashMap();
param.put("userIds",userIds);
String userResult = httpService.get(url,param);
JSONObject jsonObject = JSONObject.parseObject(userResult);
String dataStr = jsonObject.getString("data");
JSONArray userArray = JSONArray.parseArray(dataStr);
for(int i=0;i<userArray.size();i++){
JSONObject object= (JSONObject) userArray.get(i);
}
return JsonResult.buildSuccessResult("success", userArray);
}
@RequestMapping("/testKdsp")
public JsonResult testKdsp() {
String url = "http://kdsp-operation-qa2.liangkebang.net/api/kdsp/op/fa-cui/transaction-proof/query";
try {
Map<String, String> header = Maps.newHashMap();
header.put("Content-type", "application/json");
header.put("qg-tenant-id", "560761");
Map param = Maps.newHashMap();
List<Map> paramList =new ArrayList<>();
//param.put("userId", 70356062);
//param.put("orderNo", "1495958974917529600");
param.put("userId", 70356067);
param.put("orderNo", "1496312159003762688");
paramList.add(param);
//得到json字符串
String result = httpService.post(url, header, paramList);
//转换成json 对象
JSONObject json =JSONObject.parseObject(result);
String jsonResult = json.getString("data");
String businessCode = json.getString("businessCode");
if(!"0000".equals(businessCode)){
return JsonResult.buildErrorStateResult("订单信息查询报错");
}
if(jsonResult != null){
JSONObject jsonObject = JSONObject.parseObject(jsonResult);
JSONArray jsonArray = jsonObject.getJSONArray("dataList");
if(jsonArray.isEmpty()){
return JsonResult.buildErrorStateResult("未查询到对应的订单信息");
}
List<TransactionReceiptVO> transactionReceiptVOList = jsonArray.toJavaList(TransactionReceiptVO.class);
//生成pdf
String basicPath="D:\\交易凭证0222";
String filePath =basicPath +"\\"+"wuq";
FileToZip.mkdir(filePath);
filePath = filePath +"\\"+"1493905629528739840"+".pdf";
transactionReceiptRecordService.generatePDF(transactionReceiptVOList.get(0),filePath);
}
return JsonResult.buildSuccessResult("success",null);
} catch (Exception e) {
log.error("[TransactionReceiptRecordServiceImpl][exportZipFile] 网络通讯异常,userId:{},ex:{}", e.getMessage());
return JsonResult.buildErrorStateResult(e.getMessage());
}
}
/**
* 后台更新交易凭证状态
* @return
*/
@RequestMapping("/orderQuery/updateTransactionRecordsStatus")
public JsonResult updateTransactionRecordsStatus() {
return transactionReceiptRecordService.updateTransactionRecordsStatus();
}
//导出压缩包
@RequestMapping("/orderQuery/exportTransactionZipFile")
public JsonResult exportTransactionZipFile() {
try{
return transactionReceiptRecordService.exportZipFile();
}catch(Exception e){
e.printStackTrace();
return JsonResult.buildErrorStateResult("导出文件出现错误");
}
}
//pdf签章后回调接口更新pdf是否签章成功
@RequestMapping("/orderQuery/updateSignStatus")
public JsonResult updateSignStatus(@RequestBody TransactionReceiptRecordQuery query) {
try{
return transactionReceiptRecordService.updatePDFSignStatus(query.getSuccessList(),query.getFailList());
}catch(Exception e){
e.printStackTrace();
return JsonResult.buildErrorStateResult("更新签章状态失败");
}
}
}
package cn.quantgroup.customer.rest.param.transactionreceipt;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import javax.validation.constraints.NotNull;
import java.util.List;
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class TransactionReceiptRecordQuery {
/**
* 交易单号
*/
private String orderNo;
/**
* 导入状态
*/
private String importStatus;
/**
* 导出状态
*/
private String exportStatus;
/**
* 当前页数
*/
@NotNull(message = "当前页数不能为空")
private Integer pageNo;
/**
* 每页多少条数据
*/
@NotNull(message = "每页条数不能为空")
private Integer pageSize;
//更新成功list
private List<String> successList;
//更新失败list
private List<String> failList;
}
package cn.quantgroup.customer.rest.vo.transaction;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.List;
@Data
public class LogisticsVO {
/**
* 发货时间
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm")
private String postTime;
/**
* 确认收货时间
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm")
private String completeTime;
/**
* 订单状态
*/
private String statusName;
/**
* 订单类型
*/
private String typeName;
/**
* 物流公司
*/
private String expressCompany;
/**
* 物流单号
*/
private String deliveryNo;
/**
* 物流详情
*/
private List<logisticsDetailVO> detailList;
}
package cn.quantgroup.customer.rest.vo.transaction;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
@Data
public class OrderVO {
/**
* 订单号
*/
private String orderNo="/";
/**
* 供应商订单ID
*/
private String merchantOrderId ="/";
/**
* 供应链订单号
*/
private String keyStoneOrderNo="/";
/**
* 商品渠道
*/
private String skuSourceName = "/";
/**
* 下单平台
*/
private String tenantName="/";
/**
* 平台账号id
*/
private Long userId;
/**
* 平台绑定手机号
*/
private String mobile="/";
/**
* 订单创建时间
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm")
private String createdAt;
/**
* 支付完成时间
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm")
private String payTime;
/**
* 订单金额
*/
private String orderAmount;
/**
* 实付金额
*/
private String payAmount;
/**
* 支付方式
*/
private String payTypeName;
}
package cn.quantgroup.customer.rest.vo.transaction;
import lombok.Data;
@Data
public class ReceiverVO {
/**
* 收货人电话
*/
private String receiverMobile;
/**
* 收货人姓名
*/
private String receiverName;
/**
* 收货地址
*/
private String fullAddress;
}
package cn.quantgroup.customer.rest.vo.transaction;
import lombok.Data;
@Data
public class SkuVO {
/**
* 商品名称
*/
private String skuName;
/**
* 商品属性
*/
private String skuAttr;
/**
* 商品数量
*/
private String count;
}
package cn.quantgroup.customer.rest.vo.transaction;
import lombok.Data;
@Data
public class TransactionReceiptRecordVO {
private Integer userId;
private String userName;
private String serialNo;
private Integer importStatus;
private Integer exportStatus;
private String tradeNo;
private Integer id;
}
package cn.quantgroup.customer.rest.vo.transaction;
import lombok.Data;
import java.util.List;
@Data
public class TransactionReceiptVO {
/**
* 订单信息
*/
private OrderVO order;
/**
* 商品信息
*/
private List<SkuVO> skuList;
/**
* 物流信息
*/
private List<LogisticsVO> logisticsList;
/**
* 物流信息
*/
private ReceiverVO receiver;
}
package cn.quantgroup.customer.rest.vo.transaction;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
@Data
public class logisticsDetailVO {
/**
* 时间
*/
@JsonFormat(pattern="yyyy-MM-dd HH:mm")
private String time;
/**
*描述
*/
private String desc;
}
package cn.quantgroup.customer.service;
import cn.quantgroup.customer.rest.vo.transaction.TransactionReceiptRecordVO;
import cn.quantgroup.customer.rest.param.transactionreceipt.TransactionReceiptRecordQuery;
import cn.quantgroup.customer.rest.vo.JsonResult;
import cn.quantgroup.customer.rest.vo.transaction.TransactionReceiptVO;
import org.springframework.data.domain.Page;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;
public interface ITransactionReceiptRecordService {
JsonResult<Page<TransactionReceiptRecordVO>> findRecordsByQuery(TransactionReceiptRecordQuery query);
JsonResult importTransactionReceiptRecord(MultipartFile file) throws IOException;
JsonResult exportZipFile() throws Exception;
JsonResult checkCanExport();
JsonResult updateTransactionRecordsStatus();
JsonResult updatePDFSignStatus(List<String> sucessList, List<String>failList);
void generatePDF(TransactionReceiptVO transactionReceiptVO, String filePath);
}
package cn.quantgroup.customer.util;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* @author :dongjianhua
* @date :Created in 2019/10/28 10:20
* @description:excel处理工具类
* @modified By:
* @version: 1.0
*/
@Component
public class ExcelUtil {
/**
* 总行数
*/
private int totalRows = 0;
/**
* 总列数
*/
private int totalCells = 0;
/**
* 错误信息
*/
private String errorInfo;
public boolean validateExcel(String filePath) {
/** 检查文件名是否为空或者是否是Excel格式的文件 */
if (filePath == null
|| !(isExcel2003(filePath) || isExcel2007(filePath))) {
errorInfo = "文件名不是excel格式";
return false;
}
/** 检查文件是否存在 */
// File file = new File(filePath);
// if (file == null || !file.exists()) {
// errorInfo = "文件不存在";
// return false;
// }
return true;
}
public <T>List<T> read(String filename, InputStream is,Class<T> t) throws IOException {
/** 验证文件是否合法 */
if (!validateExcel(filename)) {
throw new RuntimeException("文件格式不合法 ");
}
/** 判断文件的类型,是2003还是2007 */
Workbook wb = null;
if (!isExcel2007(filename)) {
wb = new HSSFWorkbook(is);
} else {
wb = new XSSFWorkbook(is);
}
List<T> dataLst = new ArrayList<>();
/** 得到第一个shell */
Sheet sheet = wb.getSheetAt(0);
/** 得到Excel的行数 */
this.totalRows = sheet.getPhysicalNumberOfRows();
/** 得到Excel的列数 */
if (this.totalRows >= 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<String> fields = new ArrayList<>();
/** 循环Excel的行 */
for (int r = 0; r < this.totalRows; r++) {
if(r == 0){
continue;
}
Row row = sheet.getRow(r);
if (row == null) {
continue;
}
T rowLst = null;
/** 循环Excel的列 */
for (int c = 0; c < this.totalCells; c++) {
Cell cell = row.getCell(c);
String cellValue = "";
if (null != cell) {
// 以下是判断数据的类型
switch (cell.getCellType()) {
case 0: // 数字
cellValue = cell.getNumericCellValue() + "";
break;
case 1: // 字符串
cellValue = cell.getStringCellValue();
break;
case 4: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break;
case 2: // 公式
cellValue = cell.getCellFormula() + "";
break;
case 3: // 空值
cellValue = "";
break;
case 5: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
}
if(r == 1){
fields.add(cellValue);
continue;
}
if (StringUtils.isEmpty(cellValue)) {
continue;
}
if(rowLst == null){
try {
rowLst = t.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
if (c == 2||c == 5||c == 4) {
BigDecimal bd = new BigDecimal(cellValue);//要修改的值,需要string类型
cellValue = bd.setScale(0, BigDecimal.ROUND_HALF_UP).toPlainString();
}
setValue(fields.get(c),cellValue,rowLst);
}
/** 保存第r行的第c列 */
if(null != rowLst){
dataLst.add(rowLst);
}
}
return dataLst;
}
private void setValue(String field,String val, Object obj){
for (Method method : obj.getClass().getMethods()) {
if(method.getName().equalsIgnoreCase("set"+field.replace("_",""))){
try {
method.invoke(obj,val);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
break;
}
}
}
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}
package cn.quantgroup.customer.util;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 将文件夹下面的文件
* 打包成zip压缩文件
*
*
*/
public final class FileToZip {
private static final int BUFFER_SIZE = 2 * 1024;
/**
* 压缩成ZIP 单文件压缩
*
* @param srcDir
* 压缩文件夹路径
* @param out
* 压缩文件输出流
* @param KeepDirStructure
* 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException
* 压缩失败会抛出运行时异常 存在问题当源文件找不到的时候仍然压缩,
*/
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 压缩成ZIP 多文件压缩
*
* @param srcFiles
* 需要压缩的文件列表
* @param out
* 压缩文件输出流
* @throws RuntimeException
* 压缩失败会抛出运行时异常 提前判断文件是否存在
*/
public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 递归压缩方法
*
* @param sourceFile
* 源文件
* @param zos
* zip输出流
* @param name
* 压缩后的名称
* @param KeepDirStructure
* 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure)
throws Exception {
byte[] buf = new byte[BUFFER_SIZE];
if (sourceFile.isFile()) {
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();// listFiles是获取该目录下所有文件和目录的绝对路径
if (listFiles == null || listFiles.length == 0) {
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if (KeepDirStructure) {
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();//关闭当前zip条目读取下一条
}
} else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}
/**
*
* @param src 被压缩的文件源路径
* @param newSrc 压缩后的新路径+名称
* @param zipName 压缩后内层文件的名称
* @param KeepDirStructure
* 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
public static void batchCompress(String src,String newSrc,String zipName,boolean KeepDirStructure) throws Exception{
FileOutputStream fos3 = new FileOutputStream(new File(newSrc));
File file = new File(src);
ZipOutputStream zos = new ZipOutputStream(fos3);
FileToZip.compress(file, zos, zipName, KeepDirStructure);
zos.close();//切记关闭资源否则zip包出错
}
public static void main(String[] args) throws Exception {
/** 测试压缩方法1 */
/* FileOutputStream fos1 = new FileOutputStream(new File("D:/交易凭证11.zip"));
FileToZip.toZip(
"D:/交易凭证",
fos1,true);*/
/** 测试压缩方法2 */
/* List<File> fileList = new ArrayList<File>();
fileList.add(new File("F:/笔记/截图/Html/合并单元格.png"));
fileList.add(new File("F:/photo/鸡哈线/质量管理/过程质量控制/钢筋工程/fds/3D120-2018-11-14-001X号塔+桩号(承台)+钢筋工程.jpeg"));
FileOutputStream fos2 = new FileOutputStream(new File("F:/mytest02.zip"));
FileToZip.toZip(fileList, fos2);*/
/** 测试递归压缩 必须关闭zip流 */
/*FileOutputStream fos3 = new FileOutputStream(new File("F:/mytest03.zip"));
File file = new File("F:/photo/鸡哈线");
ZipOutputStream zos = new ZipOutputStream(fos3);
ZipUtils.compress(file, zos, "鸡哈线", true);
zos.close();//这里必须切记关闭
*/
List<String>list =new ArrayList();
list.add("/1王五");
list.add("/1王二");
list.add("/2王三");
list.add("/2王四");
for(String str : list){
mkdir("D:/交易凭证00"+str);
System.out.println(str);
};
}
// 创建文件上传路径
public static void mkdir(String path) {
File fd = null;
try {
fd = new File(path);
if (!fd.exists()) {
fd.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
fd = null;
}
}
}
This diff is collapsed.
package cn.quantgroup.customer.util;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.IOUtils;
public class SFTPUtil {
private final Logger logger = LoggerFactory.getLogger(SFTPUtil.class);
private ChannelSftp sftp;
private Session session;
private String username;
private String password;
private String privateKey;
private String host;
private int port;
public SFTPUtil(String username, String password, String host, int port) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
}
public SFTPUtil(String username, String host, int port, String privateKey) {
this.username = username;
this.host = host;
this.port = port;
this.privateKey = privateKey;
}
public SFTPUtil() {
}
public void login() {
try {
JSch jsch = new JSch();
if (this.privateKey != null) {
jsch.addIdentity(this.privateKey);
}
this.session = jsch.getSession(this.username, this.host, this.port);
if (this.password != null) {
this.session.setPassword(this.password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
this.session.setConfig(config);
this.session.connect();
Channel channel = this.session.openChannel("sftp");
channel.connect();
this.sftp = (ChannelSftp)channel;
this.logger.info("pwd = [{}]", this.sftp.pwd());
} catch (JSchException var4) {
var4.printStackTrace();
} catch (SftpException var5) {
var5.printStackTrace();
}
}
public void logout() {
if (this.sftp != null && this.sftp.isConnected()) {
this.sftp.disconnect();
}
if (this.session != null && this.session.isConnected()) {
this.session.disconnect();
}
}
public void upload(String basePath, String directory, String sftpFileName, InputStream input) throws SftpException {
try {
this.sftp.cd(basePath);
this.sftp.cd(directory);
} catch (SftpException var14) {
String[] dirs = directory.split("/");
String tempPath = basePath;
String[] var8 = dirs;
int var9 = dirs.length;
for(int var10 = 0; var10 < var9; ++var10) {
String dir = var8[var10];
if (null != dir && !"".equals(dir)) {
tempPath = tempPath + "/" + dir;
try {
this.sftp.cd(tempPath);
} catch (SftpException var13) {
this.sftp.mkdir(tempPath);
this.sftp.cd(tempPath);
}
}
}
}
this.sftp.put(input, sftpFileName + ".tmp");
this.sftp.rename(sftpFileName + ".tmp", sftpFileName);
}
public void download(String directory, String downloadFile, String saveDirectory, String saveFile) throws SftpException, FileNotFoundException {
if (directory != null && !"".equals(directory)) {
this.sftp.cd(directory);
}
File file = new File(saveDirectory, saveFile);
this.sftp.get(downloadFile, new FileOutputStream(file));
}
public void download(String directory, String downloadFile, File file) throws SftpException, FileNotFoundException {
if (directory != null && !"".equals(directory)) {
this.sftp.cd(directory);
}
this.sftp.get(downloadFile, new FileOutputStream(file));
}
public byte[] download(String directory, String downloadFile) throws SftpException, IOException {
if (directory != null && !"".equals(directory)) {
this.sftp.cd(directory);
}
InputStream is = this.sftp.get(downloadFile);
byte[] fileData = IOUtils.readNBytes(is, is.available());
return fileData;
}
public void delete(String directory, String deleteFile) throws SftpException {
this.sftp.cd(directory);
this.sftp.rm(deleteFile);
}
public void createDir(String createPath) {
try {
if (this.isDirExist(createPath)) {
this.sftp.cd(createPath);
return;
}
String[] pathArry = createPath.split("/");
StringBuffer filePath = new StringBuffer("/");
String[] var4 = pathArry;
int var5 = pathArry.length;
for(int var6 = 0; var6 < var5; ++var6) {
String path = var4[var6];
if (!path.equals("")) {
filePath.append(path + "/");
if (this.isDirExist(filePath.toString())) {
this.sftp.cd(filePath.toString());
} else {
this.sftp.mkdir(filePath.toString());
this.sftp.cd(filePath.toString());
}
}
}
} catch (SftpException var8) {
var8.printStackTrace();
}
}
public boolean isDirExist(String directory) {
boolean isDirExistFlag = false;
try {
SftpATTRS sftpATTRS = this.sftp.lstat(directory);
isDirExistFlag = true;
return sftpATTRS.isDir();
} catch (Exception var4) {
if (var4.getMessage().toLowerCase().equals("no such file")) {
isDirExistFlag = false;
}
return isDirExistFlag;
}
}
public Vector<?> listFiles(String directory) throws SftpException {
return this.sftp.ls(directory);
}
public static void main(String[] args) {
SFTPUtil sftp = new SFTPUtil("lhphy", "47.105.211.91", 22223, "MIIEpQIBAAKCAQEAzCJdHIHjBobXq8S+Vq6IoAY7y3u98KQ1dyA6Ixpa83bw0xZJ0yA/vrcNxueyUesdL7DaG/4kruAdiCeLukYqlmJR+SsFcBUxnB4zYSrWx106CoLjPujvv1DvFgPacDGyp4+e7ifGt/RQlAPONQ+XbaHDHjr6R/0i/93Gm+/yn+/wQvsGUVOqE4kSvpY+36mcVyAgXf2f7Q5YvGsuA7Y7wx0tqU/M/7RI2cRYa3/PumMtBAvx/3Ny17is4I+8RRCq5B/UjOiwsSd391QWMpT0B3T5tO9stpMXLL1Vfm/O4lBUIWkEJsGBqjtgLp7LUpCzDyOGW7+Bi+kDTo5Z1huvfwIDAQABAoIBAQDHcX+lnaXRN6e6NDR/fnEQYGbFjbXrSpTOOhdzOonIO9pZcvpYI7cEP9dfEfsgnGVcth6zoN/4WBGieHjFW066tX8/we/DLYHV9Y/fjLph+Mz/fhhG29F6C7o8uTEP0w6pNeJi70vxaOvdYcZ0AzLBM33uqFLmSQWMFgO5UXutFEDtgi6y6w067CFHq0LEn6PrHZqnevKsPCBMdEXQcTfDaL3JHQGGrIw7WGsi6c6uVk6EVSoSeag0mV6gLfQZzP7zf4oSTZb1Oxt10mk3hVrQV1FiNtHFQpfR9TBCrJBiRER0QQOh/PHet6lXzQ9SQbswLVsbL9asuAS7zOoFwWRBAoGBAPsjwf6waEB8YwPgL8MpD9cRd+VlwjJD9HQGSAr8IHgMNgrwhB2EZx+GOqSqI4FaXhQjb2Safs2POLZOArDmSDSajT7E6etue3c+P5MP/hprjNaSidaEcXsF/eCMjzntZT5HbHNCTHD0DoT5GkVj50UCfz3PHzQxTHV0pk4B2SufAoGBANAVuRIpwBOtF7RIDAeBi3OMdO6fTw3i3rZBco6qqGwyxt/d6BCvEGUuh3s3pcKcNfdRr6AeZRiwtgk8uu7dcwZBdF6TnCQqzJefReyVlVFDpyt44dKVDtOlckwc+BcaM56NHCWrGEJAwxAzl84rAywxktvT63x+LfY8w5KUyPAhAoGBAPM0G6fzWeIpExIrxtUuLKLPzdYfB0L6P/8kHhxVMXRQDv3lEWwsTlle+eeAxEV+J+FEt5krbGTQr9EMFtsNBxu6F9KTixxtr684XwSh1ifrw0YAPu+47tR+Zu9P71vfo83+CO5NZA12q6DmQySzrMFNu781lzhKDYspXevpKlBtAoGBALPZUrCELWPUQ5yqeNsz+JfSWm60etuBrwTP5HeywQdji8iKP73L0dviL28sVbSy12H/1FAMdUy1z2CEgP1bocNSZ4YnBtmrtFGIdCNb1kb6tk44mNYtxzbe1L88eqFdICh1xlI4YytAVlh2f0rOmltkLY6ax/o+BPPC6TaUKmiBAoGASC1VYOzpelcN0ne3RfOrTDzRH3lQzGTh7E+2UxsVpkdxJg0N4e47MGKpGyylxEiuqpcoc9w7ec+IqylcL5Hx2jzDLx4OJHagtZVv8Gx9tixG6+vAdjjl7E38HS5WQcFJzQRAyktCeeoiLYIA3UvSN0GOXqDPAkFzPtX853APRwQ=");
sftp.login();
try {
boolean has = sftp.isDirExist("./tst/20190819/account");
System.out.println(has);
if (!has) {
sftp.createDir("./tst/20190819/account");
}
} catch (Exception var3) {
var3.printStackTrace();
}
sftp.logout();
}
}
...@@ -31,7 +31,8 @@ public class WorkOrderTest { ...@@ -31,7 +31,8 @@ public class WorkOrderTest {
@Autowired @Autowired
private IWorkOrderService workOrderService; private IWorkOrderService workOrderService;
@Autowired
private IHttpService httpService;
@Test @Test
public void queryPage() { public void queryPage() {
...@@ -39,6 +40,14 @@ public class WorkOrderTest { ...@@ -39,6 +40,14 @@ public class WorkOrderTest {
System.out.println(JSONTools.serialize(pageJsonResult)); System.out.println(JSONTools.serialize(pageJsonResult));
} }
@Test
public void testUser (){
String url ="https://passportapi-qa2.liangkebang.net/api/sync/listByUserIds?userIds=70356056,70356055";
String result = httpService.get(url);
JSONObject userJsonObject = JSONObject.parseObject(userResult);
JSONObject userData = userJsonObject.getJSONObject("data");
}
public static void main(String[] args) { public static void main(String[] args) {
System.out.println(DesensitizeUtil.mobileDesensitization("13597778033")); System.out.println(DesensitizeUtil.mobileDesensitization("13597778033"));
System.out.println(DesensitizeUtil.idcardDesensitization("422802199007261711")); System.out.println(DesensitizeUtil.idcardDesensitization("422802199007261711"));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment