Commit 391b0ec2 by xunj

add README

0 parents
Showing 61 changed files with 4820 additions and 0 deletions
.idea/*
outbound.iml
*/target/*
*.iml
log/*
*.log
.DS_Store
*/.idea/*
outbound-admin/src/main/java/META-INF/MANIFEST.MF
outbound-job/src/main/java/META-INF/MANIFEST.MF
File mode changed
File mode changed
FROM java:8
EXPOSE 10301
VOLUME /tmp
ADD ./target/outbound-admin-0.0.1-SNAPSHOT.jar /app.jar
RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java","-jar","/app.jar"]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>activity</artifactId>
<groupId>com.activity</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>activity-admin</artifactId>
<dependencies>
<dependency>
<groupId>com.activity</groupId>
<artifactId>activity-common</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-net/commons-net -->
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.3</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/abc.jar</systemPath>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.16.RELEASE</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>axis</groupId>
<artifactId>axis</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.axis/axis-jaxrpc -->
<dependency>
<groupId>org.apache.axis</groupId>
<artifactId>axis-jaxrpc</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>install</defaultGoal>
<directory>target</directory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.moxi.outbound.AdminApplication</mainClass>
<includeSystemScope>true</includeSystemScope>
<jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<encoding>UTF-8</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>woff</nonFilteredFileExtension>
<nonFilteredFileExtension>eot</nonFilteredFileExtension>
<nonFilteredFileExtension>ttf</nonFilteredFileExtension>
<nonFilteredFileExtension>svg</nonFilteredFileExtension>
<nonFilteredFileExtension>xls</nonFilteredFileExtension>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.polysoft.activity;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.CrossOrigin;
import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.TimeZone;
@CrossOrigin(allowCredentials = "true", maxAge = 3600)
@SpringBootApplication
@ComponentScan(basePackages = {"com.polysoft"})
@MapperScan({"com.polysoft.activity.mapper"})
@EnableTransactionManagement
@EnableAsync
public class AdminApplication {
@PostConstruct
void setDefaultTimezone() {
TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
System.out.println("当前时间:" + new Date());
}
public static void main(String[] args) {
SpringApplication.run(AdminApplication.class, args);
}
}
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.config;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* mybatis-plus配置
*
* @author moxi moxi@xi-ai.com
*/
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
}
package com.polysoft.activity.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
factory.setReadTimeout(15000);
return factory;
}
}
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger配置
*
* @author moxi moxi@xi-ai.com
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig{
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//加了ApiOperation注解的类,生成接口文档
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//包下的类,生成接口文档
//.apis(RequestHandlerSelectors.basePackage("com.moxi.outbound.enity.job.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("宝利")
.description("宝利春节活动")
.termsOfServiceUrl("https://www.xi-ai.com")
.version("1.0.0")
.build();
}
}
\ No newline at end of file
package com.polysoft.activity.config.exception;
public class PublicException extends RuntimeException {
public PublicException(String message) {
super(message);
}
}
package com.polysoft.activity.config.exception;
import com.polysoft.activity.common.exception.RRException;
import com.polysoft.activity.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 异常处理器
*
* @author moxi moxi@xi-ai.com
*/
@RestControllerAdvice
public class RRExceptionHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 处理自定义异常
*/
@ExceptionHandler(RRException.class)
public R handleRRException(RRException e){
R r = new R();
r.put("code", e.getCode());
r.put("msg", e.getMessage());
return r;
}
@ExceptionHandler(DuplicateKeyException.class)
public R handleDuplicateKeyException(DuplicateKeyException e){
logger.error(e.getMessage(), e);
return R.error("数据库中已存在该记录");
}
@ExceptionHandler(Exception.class)
public R handleException(Exception e){
logger.error(e.getMessage(), e);
return R.error(e);
}
}
package com.polysoft.activity.constant;
public enum CallType {
NO_CALL(0,"未拨打"),
CALL_SUCCESS(1,"拨打成功"),
CALL_FAIL(-1,"拨打失败");
private Integer no;
private String desc;
CallType(Integer no,String desc){
this.no = no;
this.desc = desc;
}
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
package com.polysoft.activity.controller;
import com.polysoft.activity.service.CaseTagService;
import com.polysoft.activity.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/case")
public class CaseController {
@Autowired
private CaseTagService caseTagService;
@GetMapping("/addOrUpdate" )
@ResponseBody
public R addOrUpdateCase(String c) {
String ss = caseTagService.getSms();
return R.data(ss);
}
}
package com.polysoft.activity.entity;
import java.io.Serializable;
import java.util.Date;
public class CallResultEntity implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
//案件id
private Integer callCaseId;
//被叫人姓名
private String name;
//当前拨打伦次
private Integer rebotTime;
//案件金额
private String casePrice;
//借款应还日期
private Date returnTime;
//逾期天数
private Integer overdueDays;
//去电时间
private Date callStartTime;
//结束时间
private Date callEndTime;
//session
private String dmSessionId;
//workspace
private Integer dmWorkspaceId;
//流程id
private String intentId;
//进入意图文本
private String intentText;
//外呼号码
private String callNumber;
//分机号
private String extNumber;
//公司id
private Integer companyId;
//用户id
private Integer userId;
//拨打状态
private String callStatus;
//记录类型
private String type;
private String resultId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getCallCaseId() {
return callCaseId;
}
public void setCallCaseId(Integer callCaseId) {
this.callCaseId = callCaseId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRebotTime() {
return rebotTime;
}
public void setRebotTime(Integer rebotTime) {
this.rebotTime = rebotTime;
}
public String getCasePrice() {
return casePrice;
}
public void setCasePrice(String casePrice) {
this.casePrice = casePrice;
}
public Date getReturnTime() {
return returnTime;
}
public void setReturnTime(Date returnTime) {
this.returnTime = returnTime;
}
public Integer getOverdueDays() {
return overdueDays;
}
public void setOverdueDays(Integer overdueDays) {
this.overdueDays = overdueDays;
}
public Date getCallStartTime() {
return callStartTime;
}
public void setCallStartTime(Date callStartTime) {
this.callStartTime = callStartTime;
}
public Date getCallEndTime() {
return callEndTime;
}
public void setCallEndTime(Date callEndTime) {
this.callEndTime = callEndTime;
}
public String getDmSessionId() {
return dmSessionId;
}
public void setDmSessionId(String dmSessionId) {
this.dmSessionId = dmSessionId;
}
public Integer getDmWorkspaceId() {
return dmWorkspaceId;
}
public void setDmWorkspaceId(Integer dmWorkspaceId) {
this.dmWorkspaceId = dmWorkspaceId;
}
public String getIntentId() {
return intentId;
}
public void setIntentId(String intentId) {
this.intentId = intentId;
}
public String getIntentText() {
return intentText;
}
public void setIntentText(String intentText) {
this.intentText = intentText;
}
public String getCallNumber() {
return callNumber;
}
public void setCallNumber(String callNumber) {
this.callNumber = callNumber;
}
public String getExtNumber() {
return extNumber;
}
public void setExtNumber(String extNumber) {
this.extNumber = extNumber;
}
public Integer getCompanyId() {
return companyId;
}
public void setCompanyId(Integer companyId) {
this.companyId = companyId;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getCallStatus() {
return callStatus;
}
public void setCallStatus(String callStatus) {
this.callStatus = callStatus;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getResultId() {
return resultId;
}
public void setResultId(String resultId) {
this.resultId = resultId;
}
}
package com.polysoft.activity.mapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface CaseMapper {
String getSms();
}
package com.polysoft.activity.service;
public interface CaseTagService {
String getSms();
}
package com.polysoft.activity.service.impl;
import com.polysoft.activity.mapper.CaseMapper;
import com.polysoft.activity.service.CaseTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CaseTagServiceImpl implements CaseTagService {
@Autowired
private CaseMapper mapper;
@Override
public String getSms() {
return mapper.getSms();
}
}
package com.polysoft.activity.task;
import com.polysoft.activity.common.log.LoggerHelper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @author lvyp
* @date 2021/1/21
*/
@Component
public class EpidemicForSendWechat {
@Value("${spring.profiles.active}")
private String profile;
@Scheduled(initialDelay = 10000, fixedRate = 1*15*60*1000)
public void execute() {
try {
if (!"prod".equals(profile)) {
return;
}
Thread.sleep(10000);
sendWechat();
} catch (InterruptedException e) {
LoggerHelper.err(this.getClass(), "EpidemicForSendWechatp休眠异常:{}", e);
}
}
private void sendWechat(){
//查询疫情回访数据基础表
System.out.println("任务开始");
}
}
package com.polysoft.activity.utils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
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;
import org.apache.poi.hssf.util.HSSFCellUtil;
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.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author lee
* @description:
* @email lishuaichao@foxmail.com
* @date 2019/3/21$ 4:47 PM$
*/
public class ExcelUtil {
private static Logger log = LoggerFactory.getLogger(ExcelUtil.class);
private final static String excel2003L = ".xls"; // 2003- 版本的excel
private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel
/**
* 将流中的Excel数据转成List<Map>
*
* @param in
* 输入流
* @param fileName
* 文件名(判断Excel版本)
* @param mapping
* 字段名称映射
* @return
* @throws Exception
*/
public static List<Map<String, Object>> parseExcel(InputStream in, String fileName,
Map<String, String> mapping) throws Exception {
// 根据文件名来创建Excel工作薄
Workbook work = getWorkbook(in, fileName);
if (null == work) {
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
// 返回数据
List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();
// 遍历Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if (sheet == null)
continue;
// 取第一行标题
row = sheet.getRow(0);
String title[] = null;
if (row != null) {
title = new String[row.getLastCellNum()];
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
title[y] = (String) getCellValue(cell);
}
} else
continue;
log.info(JSON.toJSONString(title));
// 遍历当前sheet中的所有行
for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
row = sheet.getRow(j);
Map<String, Object> m = new HashMap<String, Object>();
// 遍历所有的列
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
String key = title[y];
// log.info(JSON.toJSONString(key));
m.put(mapping.get(key), getCellValue(cell));
}
ls.add(m);
}
}
work.close();
return ls;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
*
* @param inStr
* ,fileName
* @return
* @throws Exception
*/
public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if (excel2003L.equals(fileType)) {
wb = new HSSFWorkbook(inStr); // 2003-
} else if (excel2007U.equals(fileType)) {
wb = new XSSFWorkbook(inStr); // 2007+
} else {
throw new Exception("解析的文件格式有误!");
}
return wb;
}
/**
* 描述:对表格中数值进行格式化
*
* @param cell
* @return
*/
public static Object getCellValue(Cell cell) {
Object value = null;
DecimalFormat df = new DecimalFormat("0"); // 格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); // 日期格式化
DecimalFormat df2 = new DecimalFormat("0"); // 格式化数字
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if ("General".equals(cell.getCellStyle().getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
value = sdf.format(cell.getDateCellValue());
} else {
value = df2.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
break;
}
return value;
}
}
package com.polysoft.activity.utils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @description:
* @author: 李帅超
* @create: 2019-10-24 14:23
**/
public class ExportExcel {
private static Logger logger = LoggerFactory.getLogger(ExportExcel.class);
public static boolean exportExcel(HttpServletResponse response, String fileName, String title, String[] headers, List<Map> dataset, String pattern) {
boolean flag = false;
Workbook workbook = null;
if (fileName.endsWith("xlsx")) {
workbook = new XSSFWorkbook();
} else if (fileName.endsWith("xls")) {
workbook = new HSSFWorkbook();
} else {
try {
throw new Exception("invalid file name, should be xls or xlsx");
} catch (Exception e) {
logger.info("必须是xls或者xlsx结尾的文件.");
e.printStackTrace();
}
}
Sheet sheet = workbook.createSheet(title);
CellStyle style = workbook.createCellStyle();
// 列名
Row row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
Cell cell = row.createCell(i);
sheet.setColumnWidth(i, 5000);
style.setAlignment(CellStyle.ALIGN_CENTER);
cell.setCellValue(headers[i]);
}
Iterator<Map> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
Map map = it.next();
for (int num = 0; num < headers.length; num++) {
Cell cell = row.createCell(num);
Object obj = map.get(headers[num]);
if (obj instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
cell.setCellValue(sdf.format(obj));
} else if (obj instanceof Integer) {
cell.setCellValue((Integer) obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
} else {
cell.setCellValue((String) obj);
}
}
}
OutputStream os;
try {
String downloadFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
response.setContentType("application/msexcel;charset=UTF-8");
response.addHeader("Content-Disposition", "attachment;fileName=" + downloadFileName);// 设置文件名
os = response.getOutputStream();
workbook.write(os);
os.close();
flag = true;
} catch (IOException e) {
logger.info("文件写入错误");
flag = false;
e.printStackTrace();
}
return flag;
}
public static boolean saveExcel(String fileName, String title, String[] headers, List<Map> dataset, String pattern) {
boolean flag = false;
Workbook workbook = null;
if (fileName.endsWith("xlsx")) {
workbook = new XSSFWorkbook();
} else if (fileName.endsWith("xls")) {
workbook = new HSSFWorkbook();
} else {
try {
throw new Exception("invalid file name, should be xls or xlsx");
} catch (Exception e) {
logger.info("必须是xls或者xlsx结尾的文件.");
e.printStackTrace();
}
}
Sheet sheet = workbook.createSheet(title);
CellStyle style = workbook.createCellStyle();
// 列名
Row row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
Cell cell = row.createCell(i);
sheet.setColumnWidth(i, 5000);
style.setAlignment(CellStyle.ALIGN_CENTER);
cell.setCellValue(headers[i]);
}
Iterator<Map> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
Map map = it.next();
for (int num = 0; num < headers.length; num++) {
Cell cell = row.createCell(num);
Object obj = map.get(headers[num]);
if (obj instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
cell.setCellValue(sdf.format(obj));
} else if (obj instanceof Integer) {
cell.setCellValue((Integer) obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
} else {
cell.setCellValue((String) obj);
}
}
}
try (FileOutputStream fos = new FileOutputStream(fileName); OutputStream os = new BufferedOutputStream(fos)) {
workbook.write(os);
os.close();
flag = true;
} catch (IOException e) {
logger.info("文件写入错误");
flag = false;
e.printStackTrace();
}
return flag;
}
}
package com.polysoft.activity.utils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.net.ftp.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* @description:
* @author: 李帅超
* @create: 2019-07-03 16:00
**/
@Component
public class FtpUtils {
Logger logger = LoggerFactory.getLogger(FtpUtils.class);
//ftp服务器地址
@Value("${ftp.hostname}")
private String hostname;
//ftp服务器端口号默认为3379
@Value("${ftp.port}")
private Integer port;
//ftp登录账号
@Value("${ftp.username}")
private String username;
//ftp登录密码
@Value("${ftp.password}")
private String password;
@Value("${ftp.remoteDir}")
private String remoteDir;
private FTPClient ftpClient = null;
/**
* 初始化ftp服务器
*/
private void init() {
ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
try {
System.out.println("connecting...ftp服务器:" + hostname + ":" + port);
ftpClient.connect(hostname, port); //连接ftp服务器
ftpClient.login(username, password); //登录ftp服务器
int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("connect failed...ftp服务器:" + hostname + ":" + port);
}
System.out.println("connect successfu...ftp服务器:" + hostname + ":" + port);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private synchronized void keep(){
if (ftpClient == null){
init();
}
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
init();
}
try {
ftpClient.changeWorkingDirectory(remoteDir);
} catch (Exception e) {
init();
}
}
/**
* 下载文件 *
*
* @param pathname FTP服务器文件目录 *
* @param filename 文件名称 *
* @param localFile 下载后的文件路径 *
* @return
*/
public boolean downloadFile(String pathname, String filename, File localFile) {
keep();
ftpClient.enterLocalPassiveMode();
boolean flag = false;
OutputStream os = null;
try {
logger.info("开始下载文件");
//切换FTP目录
try {
ftpClient.changeWorkingDirectory(pathname);
} catch (Exception e) {
keep();
}
os = new FileOutputStream(localFile);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
//conf.setServerLanguageCode("zh");
ftpClient.setControlEncoding("UTF-8");
flag = ftpClient.retrieveFile(filename, os);
if (!flag) {
logger.info("下载文件失败");
} else {
logger.info("下载文件成功");
}
os.close();
} catch (Exception e) {
logger.info("下载文件失败" + e.getMessage());
e.printStackTrace();
} finally {
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/**
* 删除文件 *
*
* @param filename 要删除的文件名称 *
* @return
*/
public boolean deleteFile(String filename, String pathname) {
keep();
ftpClient.enterLocalPassiveMode();
boolean flag = false;
try {
ftpClient.changeWorkingDirectory(pathname);
System.out.println("开始删除文件");
flag = ftpClient.deleteFile(pathname + filename);
ftpClient.logout();
System.out.println("删除文件成功");
} catch (Exception e) {
System.out.println("删除文件失败");
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/**
* 递归遍历出目录下面所有文件
*
* @param pathName 需要遍历的目录,必须以"/"开始和结束
* @throws IOException
*/
public void list(String pathName, List<String> arFiles) throws IOException {
keep();
ftpClient.enterLocalPassiveMode();
if (pathName.startsWith("/") && pathName.endsWith("/")) {
String directory = pathName;
//更换目录到当前目录
this.ftpClient.changeWorkingDirectory(directory);
FTPFile[] files = this.ftpClient.listFiles();
for (FTPFile file : files) {
if (file.isFile()) {
arFiles.add(directory + file.getName());
} else if (file.isDirectory()) {
list(directory + file.getName() + "/", arFiles);
}
}
}
}
/**
* 递归遍历目录下面指定的文件名
*
* @param pathName 需要遍历的目录,必须以"/"开始和结束
* @param ext 文件的扩展名
* @throws IOException
*/
public void list(String pathName, String ext, List<String> arFiles) throws IOException {
ftpClient.enterLocalPassiveMode();
if (pathName.startsWith("/") && pathName.endsWith("/")) {
String directory = pathName;
//更换目录到当前目录
this.ftpClient.changeWorkingDirectory(directory);
FTPFile[] files = this.ftpClient.listFiles();
for (FTPFile file : files) {
if (file.isFile()) {
if (file.getName().endsWith(ext)) {
arFiles.add(file.getName());
}
} else if (file.isDirectory()) {
list(directory + file.getName() + "/", ext, arFiles);
}
}
}
}
public boolean unZip(File zipFile, String descDir, List<String> urlList) {
boolean flag = false;
File pathFile = new File(descDir);
if(!pathFile.exists()){
pathFile.mkdirs();
}
ZipFile zip = null;
try {
//指定编码,否则压缩包里面不能有中文目录
zip = new ZipFile(zipFile, Charset.forName("UTF-8"));
for(Enumeration entries = zip.entries(); entries.hasMoreElements();){
ZipEntry entry = (ZipEntry)entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir+zipEntryName).replace("/", File.separator);
//判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf(File.separator)));
if(!file.exists()){
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if(new File(outPath).isDirectory()){
continue;
}
//保存文件路径信息
urlList.add(outPath);
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[2048];
int len;
while((len=in.read(buf1))>0){
out.write(buf1,0,len);
}
in.close();
out.close();
}
flag = true;
//必须关闭,否则无法删除该zip文件
zip.close();
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
public void zip(String filePath, String outPath){
//输入
File file = null;
FileInputStream fis = null;
BufferedInputStream bin = null;
DataInputStream dis = null;
//输出
File outfile = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
ZipOutputStream zos = null;
ZipEntry ze = null;
try {
//输入-获取数据
file = new File(filePath);
fis = new FileInputStream(file);
bin = new BufferedInputStream(fis);
dis = new DataInputStream(bin); //增强
//输出-写出数据
outfile = new File(outPath);
fos = new FileOutputStream(outfile);
bos = new BufferedOutputStream(fos, 1024); //the buffer size
zos = new ZipOutputStream(bos); //压缩输出流
ze = new ZipEntry(file.getName()); //实体ZipEntry保存
zos.putNextEntry(ze);
int len = 0;//临时文件
byte[] bts = new byte[1024]; //读取缓冲
while((len=dis.read(bts)) != -1){ //每次读取1024个字节
System.out.println(len);
zos.write(bts, 0, len); //每次写len长度数据,最后前一次都是1024,最后一次len长度
}
System.out.println("压缩成功");
} catch (Exception e) {
e.printStackTrace();
} finally{
try { //先实例化后关闭
zos.closeEntry();
zos.close();
bos.close();
fos.close();
dis.close();
bin.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 上传文件
*
* @param pathname
* ftp服务保存地址
* @param fileName
* 上传到ftp的文件名
* @param originfilename
* 待上传文件的名称(绝对地址) *
* @return
*/
public boolean uploadFile(String pathname, String fileName, String originfilename) {
keep();
InputStream inputStream = null;
try {
System.out.println("开始上传文件");
inputStream = new FileInputStream(new File(originfilename));
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("UTF-8");
ftpClient.changeWorkingDirectory(pathname);
ftpClient.makeDirectory(pathname);
// 每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据
ftpClient.enterLocalPassiveMode();
// 观察是否真的上传成功
boolean storeFlag = ftpClient.storeFile(fileName, inputStream);
inputStream.close();
System.out.println(storeFlag?"上传文件成功true":"上传文件失败false");
return storeFlag;
} catch (Exception e) {
System.out.println("上传文件失败");
e.printStackTrace();
return false;
}
finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.polysoft.activity.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class HttpUtils {
/**
* get
*
* @param host
* @param path
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
*
* @param host
* @param path
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
*
* @param host
* @param path
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Put stream
*
* @param host
* @param path
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* 构建请求的 url
*
* @param host
* @param path
* @param querys
* @return
* @throws UnsupportedEncodingException
*/
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
if (!StringUtils.isBlank(host)) {
sbUrl.append(host);
}
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
/**
* 获取 HttpClient
*
* @param host
* @param path
* @return
*/
private static HttpClient wrapClient(String host, String path) {
HttpClient httpClient = HttpClientBuilder.create().build();
if (host != null && host.startsWith("https://")) {
return sslClient();
} else if (StringUtils.isBlank(host) && path != null && path.startsWith("https://")) {
return sslClient();
}
return httpClient;
}
/**
* 在调用SSL之前需要重写验证方法,取消检测SSL
* 创建ConnectionManager,添加Connection配置信息
*
* @return HttpClient 支持https
*/
private static HttpClient sslClient() {
try {
// 在调用SSL之前需要重写验证方法,取消检测SSL
X509TrustManager trustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
ctx.init(null, new TrustManager[]{trustManager}, null);
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
// 创建Registry
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", socketFactory).build();
// 创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig).build();
return closeableHttpClient;
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
/**
* 将结果转换成JSONObject
*
* @param httpResponse
* @return
* @throws IOException
*/
public static JSONObject getJson(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
String resp = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
return JSON.parseObject(resp);
}
public static JSONArray getJsonArray(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
String resp = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
return JSON.parseArray(resp);
}
public static String getString(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
String resp = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
return resp;
}
}
package com.polysoft.activity.utils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
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.xssf.usermodel.XSSFWorkbook;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Description: excel工具类
* @Author: 吕远征
* @CreateDate: 2020/8/14 9:41
* @Email: 344302421@qq.com
* @Version: v1.0.1
*/
public class ImportExcelUtils {
/**
* ***************导入文件,读取导入的文件内容***********
* (3:读取excel数据)读取excel文件的数据信息
* ExcelUtils.readexcell(文件路径+File.separator+newFileName, 1)
* 文件名的拼接:路径+/+新的文件名字,1
* @param startRow 读取的开始行
* @return 返回一个二维数组(第一维放的是行,第二维放的是列表)
* @throws Exception e
*/
public static String[][] readeCell(InputStream inputStream,String filename,int startRow) throws Exception{
//获取sheet
Sheet sheet = getSheet(inputStream,filename);
// 得到总行数
int rowNum = sheet.getLastRowNum()+1;
// 根据第一行获取列数
Row row = sheet.getRow(0);
//获取总列数
int colNum = row.getPhysicalNumberOfCells();
//根据行列创建二维数组
String[][] content = new String[rowNum - startRow][colNum];
String[] cols = null;
//通过循环,给二维数组赋值
for (int i = startRow; i < rowNum; i++) {
row = sheet.getRow(i);
cols = new String[colNum];
for (int j = 0; j < colNum; j++) {
//获取每个单元格的值
cols[j] = getCellValue(row.getCell(j));
//把单元格的值存入二维数组
content[i - startRow][j] =cols[j];
}
}
return content;
}
/**
* 根据表名获取第一个sheet
* @return Sheet
* @throws Exception e
*/
private static Sheet getSheet(InputStream is, String filename) throws Exception {
//文件后缀
String extension = filename.lastIndexOf(".") == -1 ? "" : filename.substring(filename.lastIndexOf("."));
//创建输入流
if (".xls".equals(extension)) {
//获取工作薄
POIFSFileSystem fs = new POIFSFileSystem(is);
return new HSSFWorkbook(fs).getSheetAt(0);
} else if (".xlsx".equals(extension) || ".xlsm".equals(extension)) {
return new XSSFWorkbook(is).getSheetAt(0);
} else {
throw new IOException("文件(" + filename + "),无法识别!");
}
}
/**
* 功能:获取单元格的值
* @param cell cell
* @return String
*/
private static String getCellValue(Cell cell) {
Object result = "";
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
// 在excel里,日期也是数字,在此要进行判断
if(HSSFDateUtil.isCellDateFormatted(cell)){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = cell.getDateCellValue();
result = sdf.format(date);
}else{
DecimalFormat df=new DecimalFormat("#");
result=df.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
result = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_FORMULA:
result = cell.getCellFormula();
break;
case Cell.CELL_TYPE_ERROR:
result = cell.getErrorCellValue();
break;
case Cell.CELL_TYPE_BLANK:
break;
default:
break;
}
}
return result.toString();
}
}
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.utils;
import java.util.HashMap;
import java.util.Map;
/**
* 返回数据
*
* @author moxi moxi@xi-ai.com
*/
public class R extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
public R() {
put("code", 200);
put("msg", "success");
}
public static R error(Exception e) {
return error(500,e.getMessage());
}
public static R error() {
return error(500, "未知异常,请联系管理员");
}
public static R error(String msg) {
return error(500, msg);
}
public static R error(int code, String msg) {
R r = new R();
r.put("code", code);
r.put("msg", msg);
return r;
}
public static R ok(String msg) {
R r = new R();
r.put("msg", msg);
return r;
}
public static R ok(Map<String, Object> map) {
R r = new R();
r.putAll(map);
return r;
}
public static R data(Object data) {
R r = R.ok();
r.put("data", data);
return r;
}
public static R ok() {
return new R();
}
@Override
public R put(String key, Object value) {
super.put(key, value);
return this;
}
}
/*
* Copyright (C) 2017 moxi, Inc. All Rights Reserved.
*/
package com.polysoft.activity.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
/**
* Created by zengwenjia on 2018/5/10.
*/
@Service
public class RestfulClient {
public static String CANRETRYNAME = "x-can-retry";
public static String CANRETRYVALUE = "true";
@Autowired
private RestTemplate restTemplate;
public <T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType,
boolean canRetry) {
ResponseEntity<T> result;
if (canRetry) {
HttpEntity<Object> entity;
if (request instanceof HttpEntity) {
entity = update((HttpEntity<Object>) request, canRetry);
} else {
HttpHeaders headers = new HttpHeaders();
headers.add(RestfulClient.CANRETRYNAME, RestfulClient.CANRETRYVALUE);
entity = new HttpEntity<>(request, headers);
}
result = restTemplate.postForEntity(url, entity, responseType);
} else {
result = restTemplate.postForEntity(url, request, responseType);
}
return result;
}
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType)
throws RestClientException {
return restTemplate.getForEntity(url, responseType);
}
private HttpEntity update(HttpEntity httpEntity, boolean canRetry) {
Object body = httpEntity.getBody();
HttpHeaders httpHeaders = httpEntity.getHeaders();
HttpHeaders tempHeaders = new HttpHeaders();
if (httpHeaders != null) {
tempHeaders.putAll(httpHeaders);
}
if (canRetry) {
tempHeaders.add(RestfulClient.CANRETRYNAME, RestfulClient.CANRETRYVALUE);
}
return new HttpEntity(body, tempHeaders);
}
}
server:
servlet:
session:
cookie:
http-only: false
tomcat:
uri-encoding: UTF-8
max-threads: 1000
min-spare-threads: 30
port: 10301
spring:
datasource:
druid:
password: Moxi123#
url: jdbc:mysql://114.112.96.30:30029/voice_quality_feichexian?useUnicode=true&characterEncoding=UTF8&useSSL=false
username: root
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
#dynamic:
# #其他数据源
# datasource:
# dm:
# #dm数据源 在相应的方法上使用 @DataSource("dm")
# password: Moxi123#
# url: jdbc:mysql://114.112.96.30:30029/voice_quality_feichexian?useUnicode=true&characterEncoding=UTF8&useSSL=false
# username: root
#mybatis
mybatis-plus:
mapper-locations: classpath:/mapper/**/*.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.moxi.outbound.enity.*.entity
global-config:
#数据库相关配置
db-config:
#主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
id-type: AUTO
#字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断"
field-strategy: NOT_NULL
logic-delete-value: -1
logic-not-delete-value: 0
banner: false
#原生配置
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
jdbc-type-for-null: 'null'
ftp:
hostname: 9.23.23.101
port: 21
username: uetlyuyinshibie
password: uetlyuyinshibie@101
remoteDir: /home/uetlyuyinshibie/10/RCV/
roadRescueRemoteDir: /home/uetlyuyinshibie/11/RCV/
#存储本地发过过去的文件
remoteDir1: /home/uetlyuyinshibie/70/SND/
localDir: /ccivol_nas/outbound/data/
#我本地
# localDir1: D:/guoshoucaitotest_mp3/data/outBoundCallPlatform/
#存储数据转文件的路径
localDir1: /ccivol_nas/outbound/data_send/
roadRescueLocalDir: /ccivol_nas/outbound/roadRescueData/
spring:
profiles:
active: prod
jackson:
date-format: yyyy-MM-dd HH:mm:ss
joda-date-time-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
enabled: true
mvc:
static-path-pattern: /upload/record/**
resources:
static-locations: file:${record.upload.url}
messages:
encoding: UTF-8
http:
encoding:
charset: UTF-8
enabled: true
force: true
datasource:
druid:
filters: stat,log4j2
#配置懒加载
mybatis.configuration.lazy-loading-enabled: true
#false 为按需加载
mybatis.configuration.aggressive-lazy-loading: false
No preview for this file type
<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
<!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="10 seconds">
<!--<include resource="org/springframework/boot/logging/logback/base.xml" />-->
<contextName>logback</contextName>
<!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义变量后,可以使“${}”来使用变量。 -->
<property name="log.path" value="logs/"/>
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter"/>
<conversionRule conversionWord="wex"
converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter"/>
<conversionRule conversionWord="wEx"
converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter"/>
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN"
value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!--输出到控制台-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>info</level>
</filter>
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--输出到文件-->
<!-- 时间滚动输出 level为 DEBUG 日志 -->
<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_debug.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志归档 -->
<fileNamePattern>${log.path}/debug/log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>7</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>debug</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 INFO 日志 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_info.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 每天日志归档路径以及格式 -->
<fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 WARN 日志 -->
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_warn.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>30</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录warn级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 ERROR 日志 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_error.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>1000</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录ERROR级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!--
<logger>用来设置某一个包或者具体的某一个类的日志打印级别、
以及指定<appender>。<logger>仅有一个name属性,
一个可选的level和一个可选的addtivity属性。
name:用来指定受此logger约束的某一个包或者具体的某一个类。
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。
如果未设置此属性,那么当前logger将会继承上级的级别。
addtivity:是否向上级logger传递打印信息。默认是true。
-->
<!--<logger name="org.springframework.web" level="info"/>-->
<!--<logger name="org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor" level="INFO"/>-->
<!--
使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
第一种把<root level="info">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
第二种就是单独给dao下目录配置debug模式,代码如下,这样配置sql语句会打印,其他还是正常info级别:
-->
<!--
root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
不能设置为INHERITED或者同义词NULL。默认是DEBUG
可以包含零个或多个元素,标识这个appender将会添加到这个logger。
-->
<!--开发环境:打印控制台-->
<springProfile name="dev">
<logger name="com.moxi" level="debug">
</logger>
</springProfile>
<springProfile name="prod">
<logger name="com.moxi" level="debug">
</logger>
</springProfile>
<springProfile name="dev">
<logger name="com.moxi" level="debug">
</logger>
</springProfile>
<root level="debug">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="WARN_FILE"/>
<appender-ref ref="ERROR_FILE"/>
</root>
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.polysoft.activity.mapper.CaseMapper">
<select id="getSms" resultType="java.lang.String">
select seat_code from t_seat_info limit 1
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>activity</artifactId>
<groupId>com.activity</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>activity-common</artifactId>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<!--用于读取excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.13</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.4.3</version>
</dependency>
<!-- 重试机制 -->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.6</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.common.exception;
/**
* 自定义异常
*
* @author moxi moxi@xi-ai.com
*/
public class RRException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String msg;
private int code = 500;
public RRException(String msg) {
super(msg);
this.msg = msg;
}
public RRException(String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public RRException(String msg, int code) {
super(msg);
this.msg = msg;
this.code = code;
}
public RRException(String msg, int code, Throwable e) {
super(msg, e);
this.msg = msg;
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
package com.polysoft.activity.common.log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>Title:</p>
* <p>Description:</p>
* <p>Copyright: Copyright (c) 2008</p>
* <p>Company: www.moxi.com</p>
*
* @author fangjianping
* @version 1.0
*/
@SuppressWarnings("unchecked")
public class LoggerHelper {
/** DOCUMENT ME! */
public static final String LOG_SPERATER = "\n---------------------------------\n";
public static final String OPERATION_LOG_NAME = "operationLog";
public static final String WSSERVICE_LOG_NAME = "wsserviceLog";
public static final String INITTASK_LOG_NAME = "initTaskLog";
public static final String ACCESS_LOG_NAME = "accseeLog";
public static final String PROJECT_INDEX_LOG_NAME = "projectIndexLog";
public static final String API_ACCESS_LOG_NAME = "apiAccessLog";
/**
* 打印起始时间
*/
public static final long TIME_LENGTH = 200L;
/**
* 字符串最大长度
*/
public static final int MAX_STR_LENGTH = 100;
/**
* Creates a new LoggerHelper object.
*/
public LoggerHelper() {
}
/**
* DOCUMENT ME!
*
* @param currentClass
* @param message 写入的日志消息
*/
public static void debug(Class currentClass, String message, Object... args) {
Logger log = LoggerFactory.getLogger(currentClass);
log.debug(message + "\r\n", args);
}
/**
* DOCUMENT ME!
*
* @param currentClass
* @param message 写入的日志消息
* @param t 记录抛出的异常信息。
*/
public static void debug(Class currentClass, String message, Throwable t) {
Logger log = LoggerFactory.getLogger(currentClass);
log.debug(message, t);
}
/**
* DOCUMENT ME!
*
* @param name
* @param message 写入的日志消息
*/
public static void debug(String name, String message, Object... args) {
Logger log = LoggerFactory.getLogger(name);
log.debug(message + "\r\n", args);
}
/**
* DOCUMENT ME!
*
* @param currentClass
* @param message 写入的日志消息
*/
public static void info(Class currentClass, String message, Object... args) {
Logger log = LoggerFactory.getLogger(currentClass);
log.info(message + "\r\n", args);
}
/**
* DOCUMENT ME!
*
* @param currentClass
* @param message 写入的日志消息
* @param t 记录抛出的异常信息。
*/
public static void info(Class currentClass, String message, Throwable t) {
Logger log = LoggerFactory.getLogger(currentClass);
log.info(message, t);
}
/**
* DOCUMENT ME!
*
* @param name
* @param message 写入的日志消息
*/
public static void info(String name, String message, Object... args) {
Logger log = LoggerFactory.getLogger(name);
log.info(message + "\r\n", args);
}
/**
* DOCUMENT ME!
*
* @param currentClass
* @param message 写入的日志消息
*/
public static void warn(Class currentClass, String message, Object... args) {
Logger log = LoggerFactory.getLogger(currentClass);
log.warn(message + "\r\n", args);
}
/**
* DOCUMENT ME!
*
* @param currentClass
* @param message 写入的日志消息
* @param t 记录抛出的异常信息。
*/
public static void warn(Class currentClass, String message, Throwable t) {
Logger log = LoggerFactory.getLogger(currentClass);
log.warn(message, t);
}
/**
* DOCUMENT ME!
*
* @param name
* @param message 写入的日志消息
*/
public static void warn(String name, String message, Object... args) {
Logger log = LoggerFactory.getLogger(name);
log.warn(message + "\r\n", args);
}
/**
* DOCUMENT ME!
*
* @param currentClass
* @param message 写入的日志消息
*/
public static void err(Class currentClass, String message, Object... args) {
Logger log = LoggerFactory.getLogger(currentClass);
log.error(message + "\r\n", args);
}
/**
* DOCUMENT ME!
*
* @param currentClass
* @param message 写入的日志消息
* @param t 记录抛出的异常信息。
*/
public static void err(Class currentClass, String message, Throwable t) {
Logger log = LoggerFactory.getLogger(currentClass);
log.error(message, t);
}
/**
* DOCUMENT ME!
*
* @param name
* @param message 写入的日志消息
*/
public static void err(String name, String message, Object... args) {
Logger log = LoggerFactory.getLogger(name);
log.error(message + "\r\n", args);
}
/**
* DOCUMENT ME!
*
* @param name
* @param message 写入的日志消息
*/
public static void err(String name, String message, Throwable t) {
Logger log = LoggerFactory.getLogger(name);
log.error(message, t);
}
}
package com.polysoft.activity.common.utils;
import com.github.pagehelper.Page;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author by zhangbr
* @date 2020/3/26.
*/
public class BeanTransferUtils {
public static <T> T transfer(Object text, Class<T> clazz) {
T t;
try {
t = clazz.newInstance();
if (text != null){
org.springframework.beans.BeanUtils.copyProperties(text, t);
}
return t;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static <T> List<T> transferList(List<?> list, Class<T> clazz) {
if(CollectionUtils.isEmpty(list)){
return Collections.emptyList();
}
List<T> result =new ArrayList<>();
for(Object each : list) {
result.add(transfer(each,clazz));
}
return result;
}
public static <T> PageResult<T> toPagedResult(List<?> list, Class<T> clazz) {
PageResult<T> result = new PageResult();
if (list instanceof Page) {
Page page = (Page)list;
result.setTotal(page.getTotal());
} else if (list != null) {
result.setTotal((long)list.size());
}
if (list != null && !list.isEmpty()) {
result.setList(transferList(list, clazz));
}
return result;
}
}
package com.polysoft.activity.common.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtils {
public static int getNumberBetweenDays(Date firstDay, Date lastDay) {
if (firstDay == null || lastDay == null) {
return 0;
}
long time = firstDay.getTime() - lastDay.getTime();
return (int) (time > 0 ? time / (24 * 60 * 60 * 1000) : 0);
}
/**
* 一天的开始时间
* @param date
* @return
*/
public static Date dayStartTime(Date date){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = dateFormat.format(date);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
return format.parse(dateStr + " 00:00:00");
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 一天的结束时间
* @param date
* @return
*/
public static Date dayEndTime(Date date){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = dateFormat.format(date);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
return format.parse(dateStr + " 23:59:59");
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
* 判断时间是否是今天
* @param date
* @return
*/
private static boolean isToday(Date date) {
//当前时间
Date now = new Date();
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
//获取今天的日期
String nowDay = sf.format(now);
//对比的时间
String day = sf.format(date);
return day.equals(nowDay);
}
}
package com.polysoft.activity.common.utils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
public class ExcelUtils {
public static Workbook transMultipartFile2WorkBook(MultipartFile file) {
try {
return file.getOriginalFilename().contains(".xlsx") ? new XSSFWorkbook(file.getInputStream()) : new HSSFWorkbook(file.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.common.utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.common.utils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
/**
* IP地址
*
* @author moxi moxi@xi-ai.com
*/
public class IPUtils {
private static Logger logger = LoggerFactory.getLogger(IPUtils.class);
/**
* 获取IP地址
*
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = null;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
logger.error("IPUtils ERROR ", e);
}
// //使用代理,则获取第一个IP地址
// if(StringUtils.isEmpty(ip) && ip.length() > 15) {
// if(ip.indexOf(",") > 0) {
// ip = ip.substring(0, ip.indexOf(","));
// }
// }
return ip;
}
}
package com.polysoft.activity.common.utils;
import io.swagger.annotations.ApiModelProperty;
/**
* @author by zhangbr
* @date 2020/6/24.
*/
public class PageQuery {
@ApiModelProperty("当前页码")
private Integer pageNum = 1;
@ApiModelProperty("每页显示条数,默认30")
private Integer pageSize = 30;
@ApiModelProperty(value = "是否分页,默认:true")
private Boolean isPage = true;
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Boolean getPage() {
return isPage;
}
public void setPage(Boolean page) {
isPage = page;
}
}
package com.polysoft.activity.common.utils;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
/**
* @author by zhangbr
* @date 2020/4/3.
*/
public class PageResult<T> {
@ApiModelProperty("数据")
private List<T> list;
@ApiModelProperty("总条数")
private long total;
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
}
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.common.utils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.List;
/**
* 分页工具类
*
* @author moxi moxi@xi-ai.com
*/
public class PageUtils implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 总记录数
*/
private int totalCount;
/**
* 每页记录数
*/
private int pageSize;
/**
* 总页数
*/
private int totalPage;
/**
* 当前页数
*/
private int currPage;
/**
* 列表数据
*/
private List<?> list;
/**
* 分页
* @param list 列表数据
* @param totalCount 总记录数
* @param pageSize 每页记录数
* @param currPage 当前页数
*/
public PageUtils(List<?> list, int totalCount, int pageSize, int currPage) {
this.list = list;
this.totalCount = totalCount;
this.pageSize = pageSize;
this.currPage = currPage;
this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
}
/**
* 分页
*/
public PageUtils(IPage<?> page) {
this.list = page.getRecords();
this.totalCount = (int)page.getTotal();
this.pageSize = (int)page.getSize();
this.currPage = (int)page.getCurrent();
this.totalPage = (int)page.getPages();
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}
package com.polysoft.activity.common.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
/**
* TODO
* lishuaichao@xi-ai.com
* 2020/7/15 10:54 上午
**/
@Component
public class PropContextUtils {
private static Environment env;
@Autowired
private void init(Environment env) {
PropContextUtils.env = env;
}
public static String getProperty(String key) {
return env.getProperty(key);
}
public static String getProperty(String key, String defaultValue) {
return env.getProperty(key, defaultValue);
}
public static <T> T getProperty(String key, Class<T> targetType) {
return env.getProperty(key, targetType);
}
public static <T> T getProperty(String key, Class<T> targetType, T defaultValue) {
return env.getProperty(key, targetType, defaultValue);
}
}
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.common.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring Context 工具类
*
* @author moxi moxi@xi-ai.com
*/
@Component
public class SpringContextUtils implements ApplicationContextAware {
public static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(String name, Class<T> requiredType) {
return applicationContext.getBean(name, requiredType);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name) {
return applicationContext.isSingleton(name);
}
public static Class<? extends Object> getType(String name) {
return applicationContext.getType(name);
}
}
\ No newline at end of file
package com.polysoft.activity.constants;
import java.util.Arrays;
public enum CallType {
CALL_TYPE_0(0, "normalConnection", "正常通话"),
CALL_TYPE_1(1, "cannotConnection", "无法接通"),
CALL_TYPE_2(2, "inputError", "OBS错误"),
CALL_TYPE_3(3, "busy", "客户忙"),
CALL_TYPE_4(4, "invalidNumber", "空号"),
CALL_TYPE_5(5, "outOfService", "暂停服务"),
CALL_TYPE_6(6, "noAnswer", "无人接听"),
CALL_TYPE_7(7, "shutDown", "停机"),
CALL_TYPE_8(8, "fail", "呼叫不成功"),
CALL_TYPE_9(9, "notYet", "未外呼"),
CALL_TYPE_10(10, "phoneIsNull", "手机号为空"),
CALL_TYPE_11(11,"waitCall","待外呼"),
CALL_TYPE_12(12,"voiceMergeError","录音拼接失败"),
CALL_TYPE_13(13,"voiceFile","录音文件下载失败"),
CALL_TYPE_14(14,"error","未知错误"),
CALL_TYPE_15(15,"paramError","参数错误"),
CALL_TYPE_16(16,"voiceNames","未检测到dm返回录音文件名称"),
CALL_TYPE_17(17,"dmError","dm报错"),
CALL_TYPE_18(18,"calling","正在拨打"),
CALL_TYPE_19(19, "turnOff", "关机"),
CALL_TYPE_20(20, "filenameError", "录音名称不存在"),
CALL_TYPE_21(21, "ttsError", "tts合成失败"),
CALL_TYPE_22(22, "sessionIdError", "sessionId已存在"),
CALL_TYPE_23(23, "callTransfer", "呼叫转移"),
CALL_TYPE_24(24, "callWaiting", "呼叫等待"),
CALL_TYPE_25(25, "refuse", "拒接"),
CALL_TYPE_26(26, "userHangUp", "用户挂断");
private Integer callTypeNum;
private String callType;
private String callTypeTitle;
public static CallType getByNum(Integer callTypeNum){
return Arrays.stream(CallType.values()).filter(type -> type.getCallTypeNum().equals(callTypeNum)).findAny().orElse(CALL_TYPE_14);
}
public static CallType getByType(String callType){
return Arrays.stream(CallType.values()).filter(type -> type.getCallType().equals(callType)).findAny().orElse(CALL_TYPE_14);
}
public static String getByCallTypeEn(String callType){
for(CallType type : CallType.values()){
if(type.callType.equals(callType)){
return type.callTypeTitle;
}
}
return "";
}
CallType(Integer callTypeNum, String callType, String callTypeTitle) {
this.callType = callType;
this.callTypeTitle = callTypeTitle;
this.callTypeNum = callTypeNum;
}
public String getCallType() {
return callType;
}
public void setCallType(String callType) {
this.callType = callType;
}
public String getCallTypeTitle() {
return callTypeTitle;
}
public void setCallTypeTitle(String callTypeTitle) {
this.callTypeTitle = callTypeTitle;
}
public Integer getCallTypeNum() {
return callTypeNum;
}
public void setCallTypeNum(Integer callTypeNum) {
this.callTypeNum = callTypeNum;
}
}
///**
// * Copyright (c) 2018 人人开源 All rights reserved.
// *
// * https://www.renren.io
// *
// * 版权所有,侵权必究!
// */
//
//package com.polysoft.activity.datasource.annotation;
//
//import java.lang.annotation.*;
//
///**
// * 多数据源注解
// *
// * @author moxi moxi@xi-ai.com
// * @since 1.0.0
// */
//@Target({ElementType.METHOD, ElementType.TYPE})
//@Retention(RetentionPolicy.RUNTIME)
//@Documented
//@Inherited
//public @interface DataSource {
// String value() default "";
//}
///**
// * Copyright (c) 2018 人人开源 All rights reserved.
// *
// * https://www.renren.io
// *
// * 版权所有,侵权必究!
// */
//
//package com.polysoft.activity.datasource.aspect;
//
//import com.polysoft.activity.datasource.annotation.DataSource;
//import com.polysoft.activity.datasource.config.DynamicContextHolder;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.annotation.Pointcut;
//import org.aspectj.lang.reflect.MethodSignature;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.core.Ordered;
//import org.springframework.core.annotation.Order;
//import org.springframework.stereotype.Component;
//
//import java.lang.reflect.Method;
//
///**
// * 多数据源,切面处理类
// *
// * @author moxi moxi@xi-ai.com
// * @since 1.0.0
// */
//@Aspect
//@Component
//@Order(Ordered.HIGHEST_PRECEDENCE)
//public class DataSourceAspect {
// protected Logger logger = LoggerFactory.getLogger(getClass());
//
// @Pointcut("@annotation(com.moxi.outbound.datasource.annotation.DataSource) " +
// "|| @within(com.moxi.outbound.datasource.annotation.DataSource)")
// public void dataSourcePointCut() {
//
// }
//
// @Around("dataSourcePointCut()")
// public Object around(ProceedingJoinPoint point) throws Throwable {
// MethodSignature signature = (MethodSignature) point.getSignature();
// Class targetClass = point.getTarget().getClass();
// Method method = signature.getMethod();
//
// DataSource targetDataSource = (DataSource)targetClass.getAnnotation(DataSource.class);
// DataSource methodDataSource = method.getAnnotation(DataSource.class);
// if(targetDataSource != null || methodDataSource != null){
// String value;
// if(methodDataSource != null){
// value = methodDataSource.value();
// }else {
// value = targetDataSource.value();
// }
//
// DynamicContextHolder.push(value);
// logger.debug("set datasource is {}", value);
// }
//
// try {
// return point.proceed();
// } finally {
// DynamicContextHolder.poll();
// logger.debug("clean datasource");
// }
// }
//}
\ No newline at end of file
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.datasource.config;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* 多数据源上下文
*
* @author moxi moxi@xi-ai.com
*/
public class DynamicContextHolder {
@SuppressWarnings("unchecked")
private static final ThreadLocal<Deque<String>> CONTEXT_HOLDER = new ThreadLocal() {
@Override
protected Object initialValue() {
return new ArrayDeque();
}
};
/**
* 获得当前线程数据源
*
* @return 数据源名称
*/
public static String peek() {
return CONTEXT_HOLDER.get().peek();
}
/**
* 设置当前线程数据源
*
* @param dataSource 数据源名称
*/
public static void push(String dataSource) {
CONTEXT_HOLDER.get().push(dataSource);
}
/**
* 清空当前线程数据源
*/
public static void poll() {
Deque<String> deque = CONTEXT_HOLDER.get();
deque.poll();
if (deque.isEmpty()) {
CONTEXT_HOLDER.remove();
}
}
}
\ No newline at end of file
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.datasource.config;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 多数据源
*
* @author moxi moxi@xi-ai.com
* @since 1.0.0
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicContextHolder.peek();
}
}
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.datasource.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.polysoft.activity.datasource.properties.DataSourceProperties;
import com.polysoft.activity.datasource.properties.DynamicDataSourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
/**
* 配置多数据源
*
* @author moxi moxi@xi-ai.com
* @since 1.0.0
*/
@Configuration
@EnableConfigurationProperties(DynamicDataSourceProperties.class)
public class DynamicDataSourceConfig {
@Autowired
private DynamicDataSourceProperties properties;
@Bean
@ConfigurationProperties(prefix = "spring.datasource.druid")
public DataSourceProperties dataSourceProperties() {
return new DataSourceProperties();
}
@Bean
public DynamicDataSource dynamicDataSource(DataSourceProperties dataSourceProperties) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setTargetDataSources(getDynamicDataSource());
//默认数据源
DruidDataSource defaultDataSource = DynamicDataSourceFactory.buildDruidDataSource(dataSourceProperties);
dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
return dynamicDataSource;
}
private Map<Object, Object> getDynamicDataSource(){
Map<String, DataSourceProperties> dataSourcePropertiesMap = properties.getDatasource();
Map<Object, Object> targetDataSources = new HashMap<>(dataSourcePropertiesMap.size());
dataSourcePropertiesMap.forEach((k, v) -> {
DruidDataSource druidDataSource = DynamicDataSourceFactory.buildDruidDataSource(v);
System.out.println("databse 初始化"+k);
targetDataSources.put(k, druidDataSource);
});
return targetDataSources;
}
}
\ No newline at end of file
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.datasource.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.polysoft.activity.datasource.properties.DataSourceProperties;
import java.sql.SQLException;
/**
* DruidDataSource
*
* @author moxi moxi@xi-ai.com
* @since 1.0.0
*/
public class DynamicDataSourceFactory {
public static DruidDataSource buildDruidDataSource(DataSourceProperties properties) {
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(properties.getDriverClassName());
druidDataSource.setUrl(properties.getUrl());
druidDataSource.setUsername(properties.getUsername());
druidDataSource.setPassword(properties.getPassword());
druidDataSource.setInitialSize(properties.getInitialSize());
druidDataSource.setMaxActive(properties.getMaxActive());
druidDataSource.setMinIdle(properties.getMinIdle());
druidDataSource.setMaxWait(properties.getMaxWait());
druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
druidDataSource.setMaxEvictableIdleTimeMillis(properties.getMaxEvictableIdleTimeMillis());
druidDataSource.setValidationQuery(properties.getValidationQuery());
druidDataSource.setValidationQueryTimeout(properties.getValidationQueryTimeout());
druidDataSource.setTestOnBorrow(properties.isTestOnBorrow());
druidDataSource.setTestOnReturn(properties.isTestOnReturn());
druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
druidDataSource.setMaxOpenPreparedStatements(properties.getMaxOpenPreparedStatements());
druidDataSource.setSharePreparedStatements(properties.isSharePreparedStatements());
try {
druidDataSource.setFilters(properties.getFilters());
druidDataSource.init();
} catch (SQLException e) {
e.printStackTrace();
}
return druidDataSource;
}
}
\ No newline at end of file
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.datasource.properties;
/**
* 多数据源属性
*
* @author moxi moxi@xi-ai.com
* @since 1.0.0
*/
public class DataSourceProperties {
private String driverClassName;
private String url;
private String username;
private String password;
/**
* Druid默认参数
*/
private int initialSize = 2;
private int maxActive = 10;
private int minIdle = -1;
private long maxWait = 60 * 1000L;
private long timeBetweenEvictionRunsMillis = 60 * 1000L;
private long minEvictableIdleTimeMillis = 1000L * 60L * 30L;
private long maxEvictableIdleTimeMillis = 1000L * 60L * 60L * 7;
private String validationQuery = "select 1";
private int validationQueryTimeout = -1;
private boolean testOnBorrow = false;
private boolean testOnReturn = false;
private boolean testWhileIdle = true;
private boolean poolPreparedStatements = false;
private int maxOpenPreparedStatements = -1;
private boolean sharePreparedStatements = false;
private String filters = "stat,wall";
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public long getMaxWait() {
return maxWait;
}
public void setMaxWait(long maxWait) {
this.maxWait = maxWait;
}
public long getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public long getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public long getMaxEvictableIdleTimeMillis() {
return maxEvictableIdleTimeMillis;
}
public void setMaxEvictableIdleTimeMillis(long maxEvictableIdleTimeMillis) {
this.maxEvictableIdleTimeMillis = maxEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public int getValidationQueryTimeout() {
return validationQueryTimeout;
}
public void setValidationQueryTimeout(int validationQueryTimeout) {
this.validationQueryTimeout = validationQueryTimeout;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public boolean isPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public int getMaxOpenPreparedStatements() {
return maxOpenPreparedStatements;
}
public void setMaxOpenPreparedStatements(int maxOpenPreparedStatements) {
this.maxOpenPreparedStatements = maxOpenPreparedStatements;
}
public boolean isSharePreparedStatements() {
return sharePreparedStatements;
}
public void setSharePreparedStatements(boolean sharePreparedStatements) {
this.sharePreparedStatements = sharePreparedStatements;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
}
\ No newline at end of file
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.datasource.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 多数据源属性
*
* @author moxi moxi@xi-ai.com
* @since 1.0.0
*/
@ConfigurationProperties(prefix = "dynamic")
public class DynamicDataSourceProperties {
private Map<String, DataSourceProperties> datasource = new LinkedHashMap<>();
public Map<String, DataSourceProperties> getDatasource() {
return datasource;
}
public void setDatasource(Map<String, DataSourceProperties> datasource) {
this.datasource = datasource;
}
}
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.polysoft.activity.utils;
/**
* 常量
*
* @author moxi moxi@xi-ai.com
*/
public class Constant {
/** 超级管理员ID */
public static final int SUPER_ADMIN = 1;
/** 数据权限过滤 */
public static final String SQL_FILTER = "sql_filter";
/**
* 当前页码
*/
public static final String PAGE = "page";
/**
* 每页显示记录数
*/
public static final String LIMIT = "limit";
/**
* 排序字段
*/
public static final String ORDER_FIELD = "sidx";
/**
* 排序方式
*/
public static final String ORDER = "order";
/**
* 升序
*/
public static final String ASC = "asc";
/**
* 菜单类型
*/
public enum MenuType {
/**
* 目录
*/
CATALOG(0),
/**
* 菜单
*/
MENU(1),
/**
* 按钮
*/
BUTTON(2);
private int value;
MenuType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* 定时任务状态
*/
public enum ScheduleStatus {
/**
* 正常
*/
NORMAL(0),
/**
* 暂停
*/
PAUSE(1);
private int value;
ScheduleStatus(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
/**
* 云服务商
*/
public enum CloudService {
/**
* 七牛云
*/
QINIU(1),
/**
* 阿里云
*/
ALIYUN(2),
/**
* 腾讯云
*/
QCLOUD(3);
private int value;
CloudService(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
}
package com.polysoft.activity.utils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
public interface Dto extends Map<String, Object> {
/**
* 以Integer类型返回属性
*
* @param pKey
* @return Integer 键值
*/
Integer getInteger(String pKey);
/**
* 以BigInteger类型返回属性
*
* @param pKey
* @return BigInteger 键值
*/
BigInteger getBigInteger(String pKey);
/**
* 以Long类型返回属性
*
* @param pKey
* @return Long 键值
*/
Long getLong(String pKey);
/**
* 以String类型返回属性
*
* @param pKey
* @return String 键值
*/
String getString(String pKey);
/**
* 以BigDecimal类型返回属性
*
* @param pKey
* @return BigDecimal 键值
*/
BigDecimal getBigDecimal(String pKey);
/**
* 以Date类型返回属性
*
* @param pKey
* @return Date 键值(yyyy-MM-dd)
*/
Date getDate(String pKey);
/**
* 以Timestamp类型返回属性
*
* @param pKey
* @return Timestamp 键值(yyyy-MM-dd HH:mm:ss)
*/
Timestamp getTimestamp(String pKey);
/**
* 以Boolean类型返回属性
*
* @param pKey
* @return Boolean 键值
*/
Boolean getBoolean(String pKey);
/**
* 以List类型返回属性
*
* @param pKey
* @return List 键值
*/
List<? extends Object> getList(String pKey);
}
//package com.moxi.outbound.utils;
//
//import java.util.Map;
//
//public class Dtos {
//
// public static Dto newDto() {
// return new HashDto();
// }
//
// public static Dto newDto(Map<String, ?> map) {
// Dto newDto = new HashDto();
// newDto.putAll(map);
// return newDto;
// }
//
// public static Dto newDto(String keyString, Object valueObject) {
// Dto dto = new HashDto();
// dto.put(keyString, valueObject);
// return dto;
// }
//
//
//}
package com.polysoft.activity.utils;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.HashMap;
import java.util.Optional;
/**
* @author lee
* @description: 上传文件到文件服务器
* @email lishuaichao@foxmail.com
* @date 2019/3/6$ 4:43 PM$
*/
@Component
public class FileServer {
private static final Logger logger = LoggerFactory.getLogger(FileServer.class);
private static final String FILE = "file";
private static final String OUTPUT = "output";
private static final String SCENE = "scene";
private static final String TYPE = "json";
private static final String OUTBOUND = "outbound";
private static String serverUrl;
@Value("${fileserver.url}")
public void setServerUrl(String serverUrl) {
FileServer.serverUrl = serverUrl;
}
public static void test() {
System.out.println(serverUrl);
}
/**
* 上传文件
*
* @param filePath
* @return
*/
public static Optional<UploadResult> upload(String filePath) {
if (StringUtils.isBlank(filePath)) {
return Optional.empty();
}
return upload(new File(filePath));
}
/**
* 上传文件到文件服务器 修改服务器url在common模块下 /config/application.yml
*
* @param file
* @return
*/
public static Optional<UploadResult> upload(File file) {
if (file == null) {
logger.error("<上传文件>上传文件失败,file不能为空");
return Optional.empty();
}
if (!file.exists()) {
logger.error("<上传文件>上传文件失败,file文件不存在");
return Optional.empty();
}
//声明参数集合
HashMap<String, Object> paramMap = new HashMap<>();
//文件
paramMap.put(FILE, file);
//输出json
paramMap.put(OUTPUT, TYPE);
//场景-外呼
paramMap.put(SCENE, OUTBOUND);
//上传
String result = null;
try {
result = HttpUtil.post(serverUrl, paramMap);
} catch (Exception e) {
e.printStackTrace();
logger.error("<上传文件>上传文件失败,ERROR:{}", e);
return Optional.empty();
}
if (StringUtils.isBlank(result)) {
logger.error("<上传文件>上传文件失败,返回结果为null");
return Optional.empty();
} else {
logger.info("<上传文件>上传文件成功,返回结果为{}", result);
}
UploadResult uploadResult = null;
try {
uploadResult = JSON.parseObject(result, UploadResult.class);
return Optional.ofNullable(uploadResult);
} catch (Exception e) {
e.printStackTrace();
logger.error("<上传文件>上传文件结果解析失败,ERROR:{}", e);
return Optional.empty();
}
}
/**
* 上传结果
*/
public static class UploadResult {
//访问
private String url;
//服务器路径
private String path;
//访问域名
private String domain;
//不带域名的路径
private String src;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
}
}
//package com.moxi.outbound.utils;
//
//import java.math.BigDecimal;
//import java.math.BigInteger;
//import java.sql.Date;
//import java.sql.Timestamp;
//import java.util.HashMap;
//import java.util.List;
//
//
//public class HashDto extends HashMap<String, Object> implements Dto {
//
//
// private static final long serialVersionUID = 1L;
//
// public HashDto() {
//
// }
//
// @Override
// public Integer getInteger(String str) {
// Object obj = TypeConvertUtil.convert(get(str), "Integer", null);
// if (obj != null)
// return (Integer) obj;
// else
// return null;
// }
//
// @Override
// public BigInteger getBigInteger(String str) {
// BigInteger outValue = null;
// Object obj = get(str);
// if (obj instanceof BigInteger) {
// outValue = (BigInteger) obj;
// } else {
// outValue = new BigInteger(getString(str));
// }
// return outValue;
// }
//
// @Override
// public Long getLong(String str) {
// Object obj = TypeConvertUtil.convert(get(str), "Long", null);
// if (obj != null)
// return (Long) obj;
// else
// return null;
// }
//
// @Override
// public String getString(String str) {
// Object obj = TypeConvertUtil.convert(get(str), "String", null);
// if (obj != null)
// return (String) obj;
// else
// return "";
// }
//
// @Override
// public BigDecimal getBigDecimal(String str) {
// Object obj = TypeConvertUtil.convert(get(str), "BigDecimal", null);
// if (obj != null)
// return (BigDecimal) obj;
// else
// return null;
// }
//
// @Override
// public Date getDate(String str) {
// Object obj = TypeConvertUtil.convert(get(str), "Date", "yyyy-MM-dd");
// if (obj != null)
// return (Date) obj;
// else
// return null;
// }
//
// @Override
// public Timestamp getTimestamp(String str) {
// Object obj = TypeConvertUtil.convert(get(str), "Timestamp", "yyyy-MM-dd HH:mm:ss");
// if (obj != null)
// return (Timestamp) obj;
// else
// return null;
// }
//
// @Override
// public Boolean getBoolean(String str) {
// Object obj = TypeConvertUtil.convert(get(str), "Boolean", null);
// if (obj != null)
// return (Boolean) obj;
// else
// return null;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public List<? extends Object> getList(String str) {
// return (List<? extends Object>) get(str);
// }
//
//}
package com.polysoft.activity.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
public class HttpUtils {
/**
* get
*
* @param host
* @param path
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
*
* @param host
* @param path
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
*
* @param host
* @param path
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Put stream
*
* @param host
* @param path
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host, path);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* 构建请求的 url
*
* @param host
* @param path
* @param querys
* @return
* @throws UnsupportedEncodingException
*/
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
if (!StringUtils.isBlank(host)) {
sbUrl.append(host);
}
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
/**
* 获取 HttpClient
*
* @param host
* @param path
* @return
*/
private static HttpClient wrapClient(String host, String path) {
HttpClient httpClient = HttpClientBuilder.create().build();
if (host != null && host.startsWith("https://")) {
return sslClient();
} else if (StringUtils.isBlank(host) && path != null && path.startsWith("https://")) {
return sslClient();
}
return httpClient;
}
/**
* 在调用SSL之前需要重写验证方法,取消检测SSL
* 创建ConnectionManager,添加Connection配置信息
*
* @return HttpClient 支持https
*/
private static HttpClient sslClient() {
try {
// 在调用SSL之前需要重写验证方法,取消检测SSL
X509TrustManager trustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
ctx.init(null, new TrustManager[]{trustManager}, null);
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
// 创建Registry
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", socketFactory).build();
// 创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig).build();
return closeableHttpClient;
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
/**
* 将结果转换成JSONObject
*
* @param httpResponse
* @return
* @throws IOException
*/
public static JSONObject getJson(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
String resp = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
return JSON.parseObject(resp);
}
public static JSONArray getJsonArray(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
String resp = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
return JSON.parseArray(resp);
}
public static String getString(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
String resp = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
return resp;
}
}
fileserver:
url: http://47.92.76.236:20000/upload
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.activity</groupId>
<artifactId>activity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<modules>
<module>activity-admin</module>
<module>activity-common</module>
</modules>
<packaging>pom</packaging>
<name>outbound</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<junit.version>4.12</junit.version>
<jedis.version>2.9.0</jedis.version>
<druid.version>1.1.10</druid.version>
<mybatisplus.version>3.0.7.1</mybatisplus.version>
<mysql.version>8.0.11</mysql.version>
<commons.lang.version>2.6</commons.lang.version>
<commons.fileupload.version>1.4</commons.fileupload.version>
<commons.io.version>2.5</commons.io.version>
<commons.codec.version>1.10</commons.codec.version>
<fastjson.version>1.2.9</fastjson.version>
<joda.time.version>2.9.9</joda.time.version>
<lombok.version>1.18.4</lombok.version>
<swagger.version>2.9.1</swagger.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatisplus.version}</version>
<exclusions>
<exclusion>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons.lang.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons.codec.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<!--逆向工程-->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<scope>test</scope>
<version>3.0.4</version>
<type>pom</type>
</dependency>
</dependencies>
<repositories>
<repository>
<id>public</id>
<name>aliyun nexus</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>aliyun nexus</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
<!-- Mybatis-Generator插件,自动生成代码 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<verbose>true</verbose>
<overwrite>false</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</plugin>
<!--添加配置跳过测试-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</project>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!