Commit 957ac6e5 by shuyunhu
parents 3d06297f 302789f6
...@@ -10,9 +10,26 @@ spring: ...@@ -10,9 +10,26 @@ spring:
loadbalancer: loadbalancer:
retry: retry:
enabled: true enabled: true
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
initialSize: 2
minIdle: 5
maxActive: 50
maxWait: 60000
timeBetweenEvictionRunsMillis: 3000
minEvictableIdleTimeMillis: 3600000
validationQuery: SELECT 'x' FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
connectionPropertiesNew: config.decrypt=true;config.decrypt.key=${spring.datasource.publicKey}
filtersNew: config
metrics: metrics:
influx: influx:
uri: http://192.168.83.241:8086/write uri: http://192.168.89.200:8086/write
step: PT10S step: PT10S
db: ${spring.application.name} db: ${spring.application.name}
enabled: true enabled: true
...@@ -32,7 +49,7 @@ spring: ...@@ -32,7 +49,7 @@ spring:
retry: retry:
max-attempts: 3 # 最大重试次数 max-attempts: 3 # 最大重试次数
enabled: true # 是否开启消费者重试(为false时关闭消费者重试,这时消费端代码异常会一直重复收到消息) enabled: true # 是否开启消费者重试(为false时关闭消费者重试,这时消费端代码异常会一直重复收到消息)
initial-interval: 5000 # 重试间隔时间(单位毫秒) initial-interval: 300000 # 重试间隔时间(单位毫秒)
default-requeue-rejected: true # 重试次数超过上面的设置之后是否丢弃(false不丢弃时需要写相应代码将该消息加入死信队列) default-requeue-rejected: true # 重试次数超过上面的设置之后是否丢弃(false不丢弃时需要写相应代码将该消息加入死信队列)
data: data:
solr: solr:
......
...@@ -86,4 +86,6 @@ uedThirdPartyOrderUrl=https://rayscloud.chubanyun.net ...@@ -86,4 +86,6 @@ uedThirdPartyOrderUrl=https://rayscloud.chubanyun.net
## \u7CFB\u7EDF\u73AF\u5883 ## \u7CFB\u7EDF\u73AF\u5883
system.env = pro system.env = pro
jsbj.agent.id = 1000009100 jsbj.agent.id = 1000009100
\ No newline at end of file
product.parentTutor.proLabelId = 7461
\ No newline at end of file
...@@ -10,9 +10,26 @@ spring: ...@@ -10,9 +10,26 @@ spring:
loadbalancer: loadbalancer:
retry: retry:
enabled: true enabled: true
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
initialSize: 2
minIdle: 5
maxActive: 50
maxWait: 60000
timeBetweenEvictionRunsMillis: 3000
minEvictableIdleTimeMillis: 3600000
validationQuery: SELECT 'x' FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
connectionPropertiesNew: config.decrypt=true;config.decrypt.key=${spring.datasource.publicKey}
filtersNew: config
metrics: metrics:
influx: influx:
uri: http://192.168.83.241:8086/write uri: http://192.168.89.200:8086/write
step: PT10S step: PT10S
db: ${spring.application.name} db: ${spring.application.name}
enabled: false enabled: false
...@@ -32,7 +49,7 @@ spring: ...@@ -32,7 +49,7 @@ spring:
retry: retry:
max-attempts: 3 # 最大重试次数 max-attempts: 3 # 最大重试次数
enabled: true # 是否开启消费者重试(为false时关闭消费者重试,这时消费端代码异常会一直重复收到消息) enabled: true # 是否开启消费者重试(为false时关闭消费者重试,这时消费端代码异常会一直重复收到消息)
initial-interval: 5000 # 重试间隔时间(单位毫秒) initial-interval: 300000 # 重试间隔时间(单位毫秒)
default-requeue-rejected: true # 重试次数超过上面的设置之后是否丢弃(false不丢弃时需要写相应代码将该消息加入死信队列) default-requeue-rejected: true # 重试次数超过上面的设置之后是否丢弃(false不丢弃时需要写相应代码将该消息加入死信队列)
data: data:
solr: solr:
......
...@@ -88,4 +88,6 @@ uedThirdPartyOrderUrl=http://deveapi.chubanyun.net ...@@ -88,4 +88,6 @@ uedThirdPartyOrderUrl=http://deveapi.chubanyun.net
## \u7CFB\u7EDF\u73AF\u5883 ## \u7CFB\u7EDF\u73AF\u5883
system.env = uat system.env = uat
jsbj.agent.id = 12829 jsbj.agent.id = 12829
\ No newline at end of file
product.parentTutor.proLabelId = 812
\ No newline at end of file
package com.pcloud.common.core.biz;
import com.pcloud.common.core.dto.BacklogQueueDto;
import com.pcloud.common.exceptions.BizException;
/**
* @描述:待办事项统计队列
* @作者:zhuyajie
* @创建时间:10:33 2018/10/31
* @版本:1.0
*/
public interface BacklogQueueBiz {
/**
* 发送待办事项
* @param backlogQueueDto
*/
public void sendBacklogQueue(BacklogQueueDto backlogQueueDto)throws BizException;
}
package com.pcloud.common.core.biz;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.constant.MQQueueConstant;
import com.pcloud.common.core.dto.BacklogQueueDto;
import com.pcloud.common.exceptions.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @描述:待办事务统计
* @作者:zhuyajie
* @创建时间:10:46 2018/10/31
* @版本:1.0
*/
@Component("backlogQueueBiz")
public class BacklogQueueBizImpl implements BacklogQueueBiz {
private final static Logger logger = LoggerFactory.getLogger(BacklogQueueBizImpl.class);
@Autowired
private AmqpTemplate amqpTemplate;
@Override
@ParamLog("发送待办事务通知")
public void sendBacklogQueue(BacklogQueueDto backlogQueueDto) throws BizException{
if (backlogQueueDto == null) {
throw BizException.PARAM_IS_NULL;
}
try {
amqpTemplate.convertAndSend(MQQueueConstant.BACKLOG, backlogQueueDto);
} catch (Exception e) {
logger.error("发送失败," + e.getMessage() + "," + backlogQueueDto.toString(), e);
throw BizException.SEND_QUEUE_FAIL;
}
}
}
...@@ -77,7 +77,12 @@ public enum AppTypeEnum { ...@@ -77,7 +77,12 @@ public enum AppTypeEnum {
/** /**
* 打卡 * 打卡
*/ */
CLOCK("clock"); CLOCK("clock"),
/**
* 伴读魔法箱
*/
AUDIO_MAGIC("magic");
......
...@@ -85,15 +85,20 @@ public enum ConvertEnum { ...@@ -85,15 +85,20 @@ public enum ConvertEnum {
*/ */
AUDIO_LESSON("AUDIO_LESSON"), AUDIO_LESSON("AUDIO_LESSON"),
/** /**
* 音频纯听 * 音频纯听
*/ */
AUDIO_LISTEN("AUDIO_LISTEN"); AUDIO_LISTEN("AUDIO_LISTEN"),
/** /**
* 值 * 音频魔法箱
*/ */
public final String value; AUDIO_MAGIC("AUDIO_MAGIC");
/**
* 值
*/
public final String value;
/** /**
* 构造 * 构造
......
...@@ -16,6 +16,11 @@ public class MQQueueConstant { ...@@ -16,6 +16,11 @@ public class MQQueueConstant {
public static final String TEMPLATE = "templateQueue"; public static final String TEMPLATE = "templateQueue";
/** /**
* 音频配音(MP3)
*/
public static final String DUBBING = "dubbingQueue";
/**
* 文件转码(PDF、OFFICE) * 文件转码(PDF、OFFICE)
*/ */
public static final String TRANSCODE = "transcodeQueue"; public static final String TRANSCODE = "transcodeQueue";
...@@ -86,6 +91,11 @@ public class MQQueueConstant { ...@@ -86,6 +91,11 @@ public class MQQueueConstant {
public static final String CONVERT_TO_AUDIOLESSON = "convert2AudioLessonQueue"; public static final String CONVERT_TO_AUDIOLESSON = "convert2AudioLessonQueue";
/** /**
* 文件转码结束(音视频)->音频课/纯听
*/
public static final String CONVERT_TO_AUDIOMAGIC = "convert2AudioMagicQueue";
/**
* 数据埋点 * 数据埋点
*/ */
public static final String FRONT_EVENT = "frontEventQueue"; public static final String FRONT_EVENT = "frontEventQueue";
...@@ -150,4 +160,9 @@ public class MQQueueConstant { ...@@ -150,4 +160,9 @@ public class MQQueueConstant {
*/ */
public static final String DEAD = "rays.dlq"; public static final String DEAD = "rays.dlq";
/**
* 待办事项数量统计
*/
public static final String BACKLOG = "backlogQueue";
} }
...@@ -16,10 +16,15 @@ public class MQTopicProducer { ...@@ -16,10 +16,15 @@ public class MQTopicProducer {
*/ */
public static final String FILE_TRANSCODE = "topic.fileTranscode"; public static final String FILE_TRANSCODE = "topic.fileTranscode";
/** /**
* 报名新增用户 * 音频配音结束(MP3)
*/ */
public static final String BM_ADD_USER = "topic.bmAddUser"; public static final String FILE_DUBBING = "topic.fileDubbing";
/**
* 报名新增用户
*/
public static final String BM_ADD_USER = "topic.bmAddUser";
/** /**
* 应用新增 * 应用新增
...@@ -70,8 +75,15 @@ public class MQTopicProducer { ...@@ -70,8 +75,15 @@ public class MQTopicProducer {
* TIP * TIP
*/ */
public static final String TIP = "topic.tip"; public static final String TIP = "topic.tip";
/** /**
* 打赏给读者
*/
public static final String TIP_FOR_WECHAT_USER = "topic.tipForWechatUser";
/**
* GENUINE
*/
public static final String GENUINE = "topic.genuine";
/**
* 订单完成 * 订单完成
*/ */
public static final String FINISH_ORDER = "topic.finishOrder"; public static final String FINISH_ORDER = "topic.finishOrder";
...@@ -266,13 +278,28 @@ public class MQTopicProducer { ...@@ -266,13 +278,28 @@ public class MQTopicProducer {
*/ */
public static final String RECORD_USER_HABIT = "topic.recordUserHabit"; public static final String RECORD_USER_HABIT = "topic.recordUserHabit";
/** /**
* topic交换机名称(勿改) * 扫码
*/ */
public static final String EXCHAGE = "rays.topic"; public static final String SCAN_QRCODE = "topic.scanQrcode";
/**
* topic交换机名称(勿改)
*/
public static final String EXCHAGE = "rays.topic";
/** /**
* 更新图书封面图 * 更新图书封面图
*/ */
public static final String UPDATE_BOOK_COVERIMG = "topic.updateBookCoverImg"; public static final String UPDATE_BOOK_COVERIMG = "topic.updateBookCoverImg";
/**
* 微信用户关系
*/
public static final String WECHAT_RELATE_INFO = "topic.wechatRelateInfo";
/**
* 更新用户头像
*/
public static final String UPDATE_USER_HEADURL = "topic.updateUserHeadUrl";
} }
...@@ -223,6 +223,21 @@ public class ProductTypeConstant { ...@@ -223,6 +223,21 @@ public class ProductTypeConstant {
public static final String EBOOK_APP = "EBOOK_APP"; public static final String EBOOK_APP = "EBOOK_APP";
/** /**
* 亲子伴读魔法箱
*/
public static final String AUDIO_MAGIC = "AUDIO_MAGIC";
/**
* 音频课
*/
public static final String AUDIO_SCHEDULE = "AUDIO_SCHEDULE";
/**
* 音频课程
*/
public static final String AUDIO_COURSE = "AUDIO_COURSE";
/**
* 热门作品类型 * 热门作品类型
*/ */
public static final String[] HOT_PRODUCT_TYPE = {QA, PDF, VIDEO, PRETEST}; public static final String[] HOT_PRODUCT_TYPE = {QA, PDF, VIDEO, PRETEST};
...@@ -231,7 +246,7 @@ public class ProductTypeConstant { ...@@ -231,7 +246,7 @@ public class ProductTypeConstant {
* 资源型作品(免费即可体验) * 资源型作品(免费即可体验)
*/ */
public static final String[] RESOURCE_PRODUCT = {AUDIO, VIDEO, PDF, EBOOK, ALBUM, PRETEST, QANEWS, public static final String[] RESOURCE_PRODUCT = {AUDIO, VIDEO, PDF, EBOOK, ALBUM, PRETEST, QANEWS,
FORMAT, WORD, ARTICLE, LISTEN, SCHEDULE, PBMUSIC, TUTORIAL, VIDEO_SCHEDULE}; FORMAT, WORD, ARTICLE, LISTEN, SCHEDULE, PBMUSIC, TUTORIAL, VIDEO_SCHEDULE, AUDIO_SCHEDULE};
/** /**
* 参与促销激励作品 * 参与促销激励作品
...@@ -248,11 +263,16 @@ public class ProductTypeConstant { ...@@ -248,11 +263,16 @@ public class ProductTypeConstant {
* 应用型作品(伴随应用使用) * 应用型作品(伴随应用使用)
*/ */
public static final String[] APP_PRODUCT = {LOOK, LIVE, TUTOR, GROUP, ZSCORE, VOTE, CLOCK, TEST, AUDIOAPP, ANSWER, public static final String[] APP_PRODUCT = {LOOK, LIVE, TUTOR, GROUP, ZSCORE, VOTE, CLOCK, TEST, AUDIOAPP, ANSWER,
EF, MUSIC, VIDEO_COURSE, PRETESTAPP, AUDIO_RESOURCE, QA_APP, EBOOK_APP}; EF, MUSIC, VIDEO_COURSE, PRETESTAPP, AUDIO_RESOURCE, QA_APP, EBOOK_APP, AUDIO_MAGIC};
/** /**
* 数据平台埋点型作品 * 数据平台埋点型作品
*/ */
public static final String[] TRACK_PRODUCT = {COMMON, AUDIO, VIDEO, PDF, EBOOK, BOOK, MATCH, ALBUM, NUMBER, MEMBER, public static final String[] TRACK_PRODUCT = {COMMON, AUDIO, VIDEO, PDF, EBOOK, BOOK, MATCH, ALBUM, NUMBER, MEMBER,
PRETEST, QANEWS, REVIEW, TOOL, QS, FORMAT, WORD, ARTICLE}; PRETEST, QANEWS, REVIEW, TOOL, QS, FORMAT, WORD, ARTICLE};
/**
* 作品下资源来源于content中心的作品
*/
public static final String[] RESOURCE_CONTENT_PRODUCT = {AUDIO,VIDEO,BOOK,LISTEN,PDF,ALBUM,FORMAT,EBOOK};
} }
...@@ -14,7 +14,8 @@ public enum RoleCodeEnum { ...@@ -14,7 +14,8 @@ public enum RoleCodeEnum {
merchant("merchant"), // 商户 merchant("merchant"), // 商户
channel("channel"), // 渠道 channel("channel"), // 渠道
agent("agent"), // 代理 agent("agent"), // 代理
adviser("adviser"); // 顾问 adviser("adviser"), // 顾问
platform("platform"); // 平台
/** /**
* 值 * 值
......
...@@ -48,6 +48,8 @@ public enum WeektaskCode { ...@@ -48,6 +48,8 @@ public enum WeektaskCode {
UPDATE_BOOK_INFO("update_book_info"), UPDATE_BOOK_INFO("update_book_info"),
//调整应用顺序 //调整应用顺序
SET_STEP("set_step"), SET_STEP("set_step"),
//确定回复
DEFINITE_REPLY("definite_reply"),
/** /**
* -------通用埋点------ * -------通用埋点------
*/ */
...@@ -139,6 +141,15 @@ public enum WeektaskCode { ...@@ -139,6 +141,15 @@ public enum WeektaskCode {
C_PUBLISH_DYNAMIC("c_publish_dynamic"), C_PUBLISH_DYNAMIC("c_publish_dynamic"),
//专题问答设置免费 //专题问答设置免费
SET_FREE("set_free"), SET_FREE("set_free"),
//选择性格心理类场景
CREATE_TEST_CHARACTER("create_test_character"),
//选择知识抢答类场景
CREATE_TEST_RESPONDER("create_test_responder"),
//读者圈中加入直播课程
W_POST_LIVEAPP_NOTE("w_post_liveapp_note"),
//创建专题扩展应用新增栏目
NEW_COLUMN("new_column"),
//----------------------------------成就任务------------------- //----------------------------------成就任务-------------------
/** /**
* 读者在读者圈中发动态 * 读者在读者圈中发动态
...@@ -651,6 +662,62 @@ public enum WeektaskCode { ...@@ -651,6 +662,62 @@ public enum WeektaskCode {
*创建抽奖应用 *创建抽奖应用
*/ */
W5_CREATE_DRAW_APP("w5_create_draw_app"), W5_CREATE_DRAW_APP("w5_create_draw_app"),
/**
*预览效果
*/
W5_CONFIGURE_NEWS("w5_configure_news"),
/**
*分享排名
*/
W5_SHARE_RANK("w5_share_rank"),
/**
* 新增性格心理类场景应用(周E3)
*/
W5_CREATE_TEST_CHARACTER("w5_create_test_character"),
/**
* 新增知识抢答类场景应用(周F3)
*/
W5_CREATE_TEST_RESPONDER("w5_create_test_responder"),
/**
* 新建直播课应用(周E4)
*/
W5_CREATE_RELATE_LIVEAPP("w5_create_relate_liveapp"),
/**
* 新建读者交流圈应用(周E5)
*/
W5_CREATE_RELATE_GROUP("w5_create_relate_group"),
/**
* 新建读书卡片应用(周E6)
*/
W5_CREATE_BOOKCARD("w5_create_bookcard"),
/**
* 新建电子书应用(周E7)
*/
W5_CREATE_EBOOK("w5_create_ebook"),
/**
* 新建分数排名应用(周F6)
*/
W5_CREATE_SCORE_APP("w5_create_score_app"),
/**
* 新建专题扩展应用(周F7)
*/
W5_CREATE_SPECIAL_APP("w5_create_special_app"),
/**
* 新建作者留言应用(周F8)
*/
W5_CREATE_VOICE_APP("w5_create_voice_app"),
/**
* 新建报名应用(周F9)
*/
W5_CREATE_BM_APP("w5_create_bm_app"),
/**
* 新建专家咨询应用(周F4)
*/
W5_CREATE_QA_APP("w5_create_qa_app"),
/**
*体验专家咨询应用(周F5)
*/
W5_EXPERIENCE_CONSULTING("w5_experience_consulting"),
; ;
public final String code; public final String code;
......
...@@ -16,6 +16,7 @@ import org.slf4j.Logger; ...@@ -16,6 +16,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
...@@ -25,139 +26,282 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; ...@@ -25,139 +26,282 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSource;
@Configuration @Configuration
@MapperScan(basePackages = DataSourceConfig.PACKAGE,sqlSessionFactoryRef = "sqlSessionFactory") @ConfigurationProperties(prefix = "spring.datasource")
@MapperScan(basePackages = DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfig { public class DataSourceConfig {
private Logger logger = LoggerFactory.getLogger(DataSourceConfig.class); private Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
static final String PACKAGE = "com.pcloud.common.core.dao"; static final String PACKAGE = "com.pcloud.common.core.dao";
@Value("${spring.datasource.url}") private String url;
private String dbUrl;
private String type;
@Value("${spring.datasource.type}")
private String dbType; private String username;
@Value("${spring.datasource.username}") private String password;
private String username;
private String driverClassName;
@Value("${spring.datasource.password}")
private String password; private int initialSize;
@Value("${spring.datasource.driver-class-name}") private int minIdle;
private String driverClassName;
private int maxActive;
@Value("${spring.datasource.initialSize}")
private int initialSize; private int maxWait;
@Value("${spring.datasource.minIdle}") private int timeBetweenEvictionRunsMillis;
private int minIdle;
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.maxActive}")
private int maxActive; private String validationQuery;
@Value("${spring.datasource.maxWait}") private boolean testWhileIdle;
private int maxWait;
private boolean testOnBorrow;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis; private boolean testOnReturn;
@Value("${spring.datasource.minEvictableIdleTimeMillis}") private boolean poolPreparedStatements;
private int minEvictableIdleTimeMillis;
private String filtersNew;
@Value("${spring.datasource.validationQuery}")
private String validationQuery; private String connectionPropertiesNew;
@Value("${spring.datasource.testWhileIdle}") @Value("${mybatis.mapper-locations}")
private boolean testWhileIdle; private String mapperLocations;
@Value("${spring.datasource.testOnBorrow}") @Value("${mybatis.type-aliases-package}")
private boolean testOnBorrow; private String typeAliasesPackage;
@Value("${spring.datasource.testOnReturn}") // @Value("${spring.datasource.useGlobalDataSourceStat}")
private boolean testOnReturn; // private boolean useGlobalDataSourceStat;
//
@Value("${spring.datasource.poolPreparedStatements}") // @Value("${spring.datasource.druidLoginName}")
private boolean poolPreparedStatements; // private String druidLoginName;
//
@Value("${spring.datasource.filters}") // @Value("${spring.datasource.druidPassword}")
private String filters; // private String druidPassword;
@Value("${spring.datasource.connectionProperties}") @Bean(name = "druidDataSource")
private String connectionProperties; @Primary // 不要漏了这
public DataSource dataSource() {
@Value("${mybatis.mapper-locations}") DruidDataSource datasource = new DruidDataSource();
private String mapperLocations; try {
datasource.setUrl(url);
@Value("${mybatis.type-aliases-package}") datasource.setDbType(type);
private String typeAliasesPackage; datasource.setUsername(username);
datasource.setPassword(password);
// @Value("${spring.datasource.useGlobalDataSourceStat}") datasource.setDriverClassName(driverClassName);
// private boolean useGlobalDataSourceStat; datasource.setInitialSize(initialSize);
// datasource.setMinIdle(minIdle);
// @Value("${spring.datasource.druidLoginName}") datasource.setMaxActive(maxActive);
// private String druidLoginName; datasource.setMaxWait(maxWait);
// datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
// @Value("${spring.datasource.druidPassword}") datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
// private String druidPassword; datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
@Bean(name="druidDataSource") datasource.setTestOnBorrow(testOnBorrow);
@Primary //不要漏了这 datasource.setTestOnReturn(testOnReturn);
public DataSource dataSource(){ datasource.setPoolPreparedStatements(poolPreparedStatements);
DruidDataSource datasource = new DruidDataSource(); datasource.setFilters(filtersNew);
try { datasource.setConnectionProperties(connectionPropertiesNew);
datasource.setUrl(this.dbUrl); // datasource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);
datasource.setDbType(dbType); ArrayList<String> arr = new ArrayList<>();
datasource.setUsername(username); arr.add("set names utf8mb4;");
datasource.setPassword(password); datasource.setConnectionInitSqls(arr);
datasource.setDriverClassName(driverClassName); } catch (SQLException e) {
datasource.setInitialSize(initialSize); logger.error("druid configuration initialization filter", e);
datasource.setMinIdle(minIdle); }
datasource.setMaxActive(maxActive); return datasource;
datasource.setMaxWait(maxWait); }
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); @Bean(name = "transactionManager")
datasource.setValidationQuery(validationQuery); public DataSourceTransactionManager transactionManager() {
datasource.setTestWhileIdle(testWhileIdle); logger.info("【DataSource】初始化TransactionManager事务管理器,<START>");
datasource.setTestOnBorrow(testOnBorrow); return new DataSourceTransactionManager(dataSource());
datasource.setTestOnReturn(testOnReturn); }
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setFilters(filters); @Bean(name = "sqlSessionFactory")
datasource.setConnectionProperties(connectionProperties); @Autowired
// datasource.setUseGlobalDataSourceStat(useGlobalDataSourceStat); public SqlSessionFactory sqlSessionFactory(ExecutorInterceptor interceptor) throws Exception {
ArrayList<String> arr = new ArrayList<>(); logger.info("【DataSource】初始化SqlSessionFactory,<START>");
arr.add("set names utf8mb4;"); final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
datasource.setConnectionInitSqls(arr); sessionFactoryBean.setDataSource(dataSource());
} catch (SQLException e) { sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
logger.error("druid configuration initialization filter", e); sessionFactoryBean.setVfs(SpringBootVFS.class);
} sessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
return datasource; sessionFactoryBean.setPlugins(new Interceptor[] { interceptor });
} return sessionFactoryBean.getObject();
}
@Bean(name = "transactionManager")
public DataSourceTransactionManager transactionManager() { @Bean(name = "sqlSessionTemplate")
logger.info("【DataSource】初始化TransactionManager事务管理器,<START>"); @Autowired
return new DataSourceTransactionManager(dataSource()); public SqlSessionTemplate sqlSessionTemplate(ExecutorInterceptor interceptor) throws Exception {
} logger.info("【DataSource】初始化SqlSessionTemplate,<START>");
final SqlSessionTemplate sessionFactoryBean = new SqlSessionTemplate(sqlSessionFactory(interceptor));
return sessionFactoryBean;
@Bean(name = "sqlSessionFactory") }
@Autowired
public SqlSessionFactory sqlSessionFactory(ExecutorInterceptor interceptor) throws Exception { public String getUrl() {
logger.info("【DataSource】初始化SqlSessionFactory,<START>"); return url;
final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean(); }
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations)); public void setUrl(String url) {
sessionFactoryBean.setVfs(SpringBootVFS.class); this.url = url;
sessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage); }
sessionFactoryBean.setPlugins(new Interceptor[]{interceptor});
return sessionFactoryBean.getObject(); public String getType() {
} return type;
}
@Bean(name = "sqlSessionTemplate")
@Autowired public void setType(String type) {
public SqlSessionTemplate sqlSessionTemplate(ExecutorInterceptor interceptor) throws Exception { this.type = type;
logger.info("【DataSource】初始化SqlSessionTemplate,<START>"); }
final SqlSessionTemplate sessionFactoryBean = new SqlSessionTemplate(sqlSessionFactory(interceptor));
return sessionFactoryBean; 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 String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMaxWait() {
return maxWait;
}
public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
public int getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public int getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
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 isPoolPreparedStatements() {
return poolPreparedStatements;
}
public void setPoolPreparedStatements(boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public String getFiltersNew() {
return filtersNew;
}
public void setFiltersNew(String filtersNew) {
this.filtersNew = filtersNew;
}
public String getConnectionPropertiesNew() {
return connectionPropertiesNew;
}
public void setConnectionPropertiesNew(String connectionPropertiesNew) {
this.connectionPropertiesNew = connectionPropertiesNew;
}
public String getMapperLocations() {
return mapperLocations;
}
public void setMapperLocations(String mapperLocations) {
this.mapperLocations = mapperLocations;
}
public String getTypeAliasesPackage() {
return typeAliasesPackage;
}
public void setTypeAliasesPackage(String typeAliasesPackage) {
this.typeAliasesPackage = typeAliasesPackage;
}
} }
package com.pcloud.common.core.dto;
import java.io.Serializable;
/**
* @描述:待办事务统计
* @作者:zhuyajie
* @创建时间:10:36 2018/10/31
* @版本:1.0
*/
public class BacklogQueueDto implements Serializable{
/**
* 编辑id
*/
private Long adviserId;
/**
* 应用id或商品id
*/
private Long targetId;
/**
*类型(APP/PRODUCT)
*/
private String targetType;
/**
*封面图
*/
private String coverImg;
/**
*标题
*/
private String title;
/**
*待审核/确认数量
*/
private Integer waitCount;
/**
*新动态数量
*/
private Integer newCount;
/**
*应用/商品类型编码
*/
private String typeCode;
public Long getAdviserId() {
return adviserId;
}
public void setAdviserId(Long adviserId) {
this.adviserId = adviserId;
}
public Long getTargetId() {
return targetId;
}
public void setTargetId(Long targetId) {
this.targetId = targetId;
}
public String getTargetType() {
return targetType;
}
public void setTargetType(String targetType) {
this.targetType = targetType;
}
public String getCoverImg() {
return coverImg;
}
public void setCoverImg(String coverImg) {
this.coverImg = coverImg;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getWaitCount() {
return waitCount;
}
public void setWaitCount(Integer waitCount) {
this.waitCount = waitCount;
}
public Integer getNewCount() {
return newCount;
}
public void setNewCount(Integer newCount) {
this.newCount = newCount;
}
public String getTypeCode() {
return typeCode;
}
public void setTypeCode(String typeCode) {
this.typeCode = typeCode;
}
@Override
public String toString() {
return "BacklogQueueDto{" +
"adviserId=" + adviserId +
", targetId=" + targetId +
", targetType='" + targetType + '\'' +
", coverImg='" + coverImg + '\'' +
", title='" + title + '\'' +
", waitCount=" + waitCount +
", newCount=" + newCount +
", typeCode='" + typeCode + '\'' +
'}';
}
}
...@@ -9,216 +9,232 @@ import java.io.Serializable; ...@@ -9,216 +9,232 @@ import java.io.Serializable;
/** /**
* @描述: * @描述:
*
* @作者:songx * @作者:songx
* @创建时间:2017年2月27日,上午11:23:29 @版本:1.0 * @创建时间:2017年2月27日,上午11:23:29 @版本:1.0
*/ */
public class ConvertQueueDto implements Serializable { public class ConvertQueueDto implements Serializable {
/** /**
* *
*/ */
private static final long serialVersionUID = 7968821573480010447L; private static final long serialVersionUID = 7968821573480010447L;
/** /**
* 标识 * 标识
*/ */
private Long id; private Long id;
/** /**
* 文件UUID * 文件UUID
*/ */
private String fileId; private String fileId;
/** /**
* 来源类型 * 来源类型
*/ */
private String fromType; private String fromType;
/** /**
* 自定义类型,fromType的二级类型 * 自定义类型,fromType的二级类型
*/ */
@ApiModelProperty(name = "自定义类型", dataType = "String") @ApiModelProperty(name = "自定义类型", dataType = "String")
private String customType; private String customType;
/** /**
* 来源标识 * 视频截图时间点
*/ */
private Long fromId; private int snapshotTime;
/** /**
* 文件路径 * 来源标识
*/ */
private String fileUrl; private Long fromId;
/** /**
* 文件大小 * 文件路径
*/ */
private Long fileSize; private String fileUrl;
/** /**
* 文件类型 * 文件大小
*/ */
private String fileType; private Long fileSize;
/** /**
* 在缓存中被处理的次数 * 文件类型
*/ */
private int processTimes = 0; private String fileType;
/** /**
* 转换成功标记,true:成功,false失败 * 在缓存中被处理的次数
*/ */
private Boolean state; private int processTimes = 0;
/** /**
* 封面图 * 转换成功标记,true:成功,false失败
*/ */
private String coverImg; private Boolean state;
/** /**
* 使用地址 * 封面图
*/ */
private String pilotUrl; private String coverImg;
/** /**
* 视频时长 * 使用地址
*/ */
private Integer duration; private String pilotUrl;
/** /**
* 视频m3u8地址 * 视频时长
*/ */
private String m3u8Url; private Integer duration;
public String getCustomType() { /**
return customType; * 视频m3u8地址
} */
private String m3u8Url;
public void setCustomType(String customType) {
this.customType = customType; public int getSnapshotTime() {
} return snapshotTime;
}
public String getM3u8Url() {
return m3u8Url; public void setSnapshotTime(int snapshotTime) {
} this.snapshotTime = snapshotTime;
}
public void setM3u8Url(String m3u8Url) {
this.m3u8Url = m3u8Url; public String getCustomType() {
} return customType;
}
public Integer getDuration() {
return duration; public void setCustomType(String customType) {
} this.customType = customType;
}
public void setDuration(Integer duration) {
this.duration = duration; public String getM3u8Url() {
} return m3u8Url;
}
public Long getFromId() {
return fromId; public void setM3u8Url(String m3u8Url) {
} this.m3u8Url = m3u8Url;
}
public void setFromId(Long fromId) {
this.fromId = fromId; public Integer getDuration() {
} return duration;
}
public String getPilotUrl() {
return pilotUrl; public void setDuration(Integer duration) {
} this.duration = duration;
}
public void setPilotUrl(String pilotUrl) {
this.pilotUrl = pilotUrl; public Long getFromId() {
} return fromId;
}
public String getCoverImg() {
return coverImg; public void setFromId(Long fromId) {
} this.fromId = fromId;
}
public void setCoverImg(String coverImg) {
this.coverImg = coverImg; public String getPilotUrl() {
} return pilotUrl;
}
public Boolean getState() {
return state; public void setPilotUrl(String pilotUrl) {
} this.pilotUrl = pilotUrl;
}
public void setState(Boolean state) {
this.state = state; public String getCoverImg() {
} return coverImg;
}
public String getFileType() {
return fileType; public void setCoverImg(String coverImg) {
} this.coverImg = coverImg;
}
public void setFileType(String fileType) {
this.fileType = fileType; public Boolean getState() {
} return state;
}
public Long getId() {
return id; public void setState(Boolean state) {
} this.state = state;
}
public void setId(Long id) {
this.id = id; public String getFileType() {
} return fileType;
}
public String getFileId() {
return fileId; public void setFileType(String fileType) {
} this.fileType = fileType;
}
public void setFileId(String fileId) {
this.fileId = fileId; public Long getId() {
} return id;
}
public String getFromType() {
return fromType; public void setId(Long id) {
} this.id = id;
}
public void setFromType(String fromType) {
this.fromType = fromType; public String getFileId() {
} return fileId;
}
/**
* @return Returns the fileUrl. public void setFileId(String fileId) {
*/ this.fileId = fileId;
public String getFileUrl() { }
return fileUrl;
} public String getFromType() {
return fromType;
/** }
* @param fileUrl The fileUrl to set.
*/ public void setFromType(String fromType) {
public void setFileUrl(String fileUrl) { this.fromType = fromType;
this.fileUrl = fileUrl; }
}
/**
/** * @return Returns the fileUrl.
* @return Returns the fileSize. */
*/ public String getFileUrl() {
public Long getFileSize() { return fileUrl;
return fileSize; }
}
/**
/** * @param fileUrl
* @param fileSize The fileSize to set. * The fileUrl to set.
*/ */
public void setFileSize(Long fileSize) { public void setFileUrl(String fileUrl) {
this.fileSize = fileSize; this.fileUrl = fileUrl;
} }
public int getProcessTimes() { /**
return processTimes; * @return Returns the fileSize.
} */
public Long getFileSize() {
public void setProcessTimes(int processTimes) { return fileSize;
this.processTimes = processTimes; }
}
/**
@Override * @param fileSize
public String toString() { * The fileSize to set.
return "ConvertQueueDto [fileId=" + fileId + ", fromType=" + fromType + ", fileUrl=" + fileUrl + ", fileSize=" */
+ fileSize + ", fileType=" + fileType + ", state=" + state + ", coverImg=" + coverImg + ", pilotUrl=" public void setFileSize(Long fileSize) {
+ pilotUrl + "]"; this.fileSize = fileSize;
} }
public int getProcessTimes() {
return processTimes;
}
public void setProcessTimes(int processTimes) {
this.processTimes = processTimes;
}
@Override
public String toString() {
return "ConvertQueueDto [fileId=" + fileId + ", fromType=" + fromType + ", fileUrl=" + fileUrl + ", fileSize="
+ fileSize + ", fileType=" + fileType + ", state=" + state + ", coverImg=" + coverImg + ", pilotUrl="
+ pilotUrl + "]";
}
} }
...@@ -32,6 +32,14 @@ public class SendAppMessageDto implements Serializable{ ...@@ -32,6 +32,14 @@ public class SendAppMessageDto implements Serializable{
* 模板参数 * 模板参数
*/ */
private Map<String, Object> paramKeyMap; private Map<String, Object> paramKeyMap;
/**
* 设备类型
*/
private String deviceType;
/**
* 应用id
*/
private Long appId;
public String getRegistrationId() { public String getRegistrationId() {
return registrationId; return registrationId;
...@@ -64,12 +72,35 @@ public class SendAppMessageDto implements Serializable{ ...@@ -64,12 +72,35 @@ public class SendAppMessageDto implements Serializable{
public void setIsNow(Boolean isNow) { public void setIsNow(Boolean isNow) {
this.isNow = isNow; this.isNow = isNow;
} }
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public Long getAppId() {
return appId;
}
public void setAppId(Long appId) {
this.appId = appId;
}
@Override @Override
public String toString() { public String toString() {
return "SendAppMessageDto [registrationId=" + registrationId + ", adviserId=" + adviserId + ", typeCode=" return "SendAppMessageDto{" +
+ typeCode + ", isNow=" + isNow + ", paramKeyMap=" + paramKeyMap + "]"; "registrationId='" + registrationId + '\'' +
", adviserId=" + adviserId +
", typeCode='" + typeCode + '\'' +
", isNow=" + isNow +
", paramKeyMap=" + paramKeyMap +
", deviceType='" + deviceType + '\'' +
", appId=" + appId +
'}';
} }
} }
/**
*
*/
package com.pcloud.common.core.dto.dubbing;
import java.io.Serializable;
import com.alibaba.fastjson.JSONObject;
/**
*
* @author:songx
* @date:2018年12月5日,下午5:07:40
*/
public class AudioDTO implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1217229671463911762L;
/**
* 文件名称
*/
private String fileName;
/**
* 时长
*/
private int duration;
/**
* 文件地址
*/
private String fileUrl;
/**
* 文件大小
*/
private long fileSize;
/**
* 语音文件插入时间点
*/
private int start;
/**
* id
*/
private int id;
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getFileUrl() {
return fileUrl;
}
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
@Override
public String toString() {
return "DubbingResultDTO : " + JSONObject.toJSONString(this);
}
}
package com.pcloud.common.core.dto.dubbing;
import java.io.Serializable;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
/**
* 绘本配音资源DTO
*
* @author:songx
* @date:2018年12月5日,上午10:07:26
*/
public class DubbingDTO implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5639047705106025465L;
/**
* 用户添加的问题文本(不超过5条)
*/
private List<SpeechDTO> speechDTOs;
/**
* 待合成的背景音乐URL(不超过4条)
*/
private String[] bgms;
/**
* 录音文件地址
*/
private String soundUrl;
/**
* 来源类型
*/
private String fromType;
/**
* 导语
*/
private String beforeText;
/**
* 结束语
*/
private String afterText;
/**
* 应用ID
*/
private Long appId;
/**
* 编辑ID
*/
private Long adviserId;
/**
* 音乐ID
*/
private Long musicId;
public String getSoundUrl() {
return soundUrl;
}
public void setSoundUrl(String soundUrl) {
this.soundUrl = soundUrl;
}
public String getFromType() {
return fromType;
}
public void setFromType(String fromType) {
this.fromType = fromType;
}
public String getBeforeText() {
return beforeText;
}
public void setBeforeText(String beforeText) {
this.beforeText = beforeText;
}
public String getAfterText() {
return afterText;
}
public void setAfterText(String afterText) {
this.afterText = afterText;
}
public Long getAppId() {
return appId;
}
public void setAppId(Long appId) {
this.appId = appId;
}
public Long getAdviserId() {
return adviserId;
}
public void setAdviserId(Long adviserId) {
this.adviserId = adviserId;
}
public Long getMusicId() {
return musicId;
}
public void setMusicId(Long musicId) {
this.musicId = musicId;
}
public List<SpeechDTO> getSpeechDTOs() {
return speechDTOs;
}
public void setSpeechDTOs(List<SpeechDTO> speechDTOs) {
this.speechDTOs = speechDTOs;
}
public String[] getBgms() {
return bgms;
}
public void setBgms(String[] bgms) {
this.bgms = bgms;
}
@Override
public String toString() {
return "DubbingDTO : " + JSONObject.toJSONString(this);
}
}
package com.pcloud.common.core.dto.dubbing;
import com.alibaba.fastjson.JSONObject;
import com.pcloud.common.core.dto.dubbing.AudioDTO;
import java.io.Serializable;
import java.util.List;
/**
* 绘本配音资源DTO
*
* @author:songx
* @date:2018年12月5日,上午10:07:26
*/
public class DubbingResultDTO implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2458000180158610651L;
/**
* 来源类型
*/
private String fromType;
/**
* 语音文件
*/
private List<AudioDTO> speechs;
/**
* 混合音频
*/
private AudioDTO mixAudio;
/**
* 应用ID
*/
private Long appId;
/**
* 编辑ID
*/
private Long adviserId;
/**
* 音乐ID
*/
private Long musicId;
public String getFromType() {
return fromType;
}
public void setFromType(String fromType) {
this.fromType = fromType;
}
public Long getAppId() {
return appId;
}
public void setAppId(Long appId) {
this.appId = appId;
}
public Long getAdviserId() {
return adviserId;
}
public void setAdviserId(Long adviserId) {
this.adviserId = adviserId;
}
public Long getMusicId() {
return musicId;
}
public void setMusicId(Long musicId) {
this.musicId = musicId;
}
public List<AudioDTO> getSpeechs() {
return speechs;
}
public void setSpeechs(List<AudioDTO> speechs) {
this.speechs = speechs;
}
public AudioDTO getMixAudio() {
return mixAudio;
}
public void setMixAudio(AudioDTO mixAudio) {
this.mixAudio = mixAudio;
}
@Override
public String toString() {
return "DubbingResultDTO : " + JSONObject.toJSONString(this);
}
}
/**
*
*/
package com.pcloud.common.core.dto.dubbing;
import java.io.Serializable;
import com.alibaba.fastjson.JSONObject;
/**
*
* @author:songx
* @date:2018年12月5日,下午5:05:57
*/
public class SpeechDTO implements Serializable{
/**
*
*/
private static final long serialVersionUID = -5054460976926789378L;
/**
* 文本内容
*/
private String text;
/**
* id
*/
private int id;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "SpeechDTO : " + JSONObject.toJSONString(this);
}
}
\ No newline at end of file
package com.pcloud.common.core.enums;
/**
* @描述:代办事务类型
* @作者:zhuyajie
* @创建时间:10:54 2018/10/31
* @版本:1.0
*/
public enum BacklogTypeEnum {
/**
* 应用
*/
APP("APP"),
/**
* 作品
*/
PRODUCT("PRODUCT");
private String value;
public String getValue() {
return value;
}
BacklogTypeEnum(String value) {
this.value = value;
}
}
...@@ -42,7 +42,17 @@ public enum TranscodeFromEnum { ...@@ -42,7 +42,17 @@ public enum TranscodeFromEnum {
/** /**
* 直播 * 直播
*/ */
LIVE_HOMEWORD("LIVE_HOMEWORD"); LIVE_HOMEWORD("LIVE_HOMEWORD"),
/**
* 音频
*/
AUDIOAPP_PDF("AUDIOAPP_PDF"),
/**
* 文件管理中心
*/
CONVERT_PDF("CONVERT_PDF");
/** /**
* 值 * 值
......
...@@ -9,7 +9,10 @@ import org.slf4j.LoggerFactory; ...@@ -9,7 +9,10 @@ import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
...@@ -22,6 +25,8 @@ import com.pcloud.common.permission.PermissionException; ...@@ -22,6 +25,8 @@ import com.pcloud.common.permission.PermissionException;
import feign.FeignException; import feign.FeignException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import java.util.List;
/** /**
* *
* @描述:异常集中处理 * @描述:异常集中处理
...@@ -92,6 +97,23 @@ public class GlobalExceptionHandler { ...@@ -92,6 +97,23 @@ public class GlobalExceptionHandler {
LOGGER.warn("【响应未结束】" + exception.getMessage(), exception); LOGGER.warn("【响应未结束】" + exception.getMessage(), exception);
return new ResponseEntity<>("响应未结束!", HttpStatus.OK); return new ResponseEntity<>("响应未结束!", HttpStatus.OK);
} }
else if (exception instanceof MethodArgumentNotValidException) {
LOGGER.info("【参数异常】" + exception.getMessage(), exception);
MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) exception;
ResponseDto<Object> responseDto = new ResponseDto<>();
BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
String resultMessage = "参数异常:";
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
for (int i = 0;i<fieldErrors.size();i++) {
if(fieldErrors.size()==1 || i == fieldErrors.size()-1){
resultMessage += fieldErrors.get(i).getDefaultMessage();
}else {
resultMessage += fieldErrors.get(i).getDefaultMessage() + ", ";
}
}
responseDto.setMessage(resultMessage);
return new ResponseEntity<>(responseDto, HttpStatus.OK);
}
// 业务异常 // 业务异常
else if (exception instanceof BizException) { else if (exception instanceof BizException) {
LOGGER.info("【业务异常】" + exception.getMessage(), exception); LOGGER.info("【业务异常】" + exception.getMessage(), exception);
......
...@@ -178,6 +178,10 @@ ...@@ -178,6 +178,10 @@
<artifactId>httpcore</artifactId> <artifactId>httpcore</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId> <groupId>redis.clients</groupId>
<artifactId>jedis</artifactId> <artifactId>jedis</artifactId>
</dependency> </dependency>
...@@ -291,13 +295,6 @@ ...@@ -291,13 +295,6 @@
<artifactId>aliyun-java-sdk-mts</artifactId> <artifactId>aliyun-java-sdk-mts</artifactId>
</dependency> </dependency>
<!-- solr add by gaop at 2018-4-23 11:33:47 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
</dependency>
<!-- end -->
<!-- Jackson Begin --> <!-- Jackson Begin -->
<dependency> <dependency>
<groupId>org.codehaus.jackson</groupId> <groupId>org.codehaus.jackson</groupId>
...@@ -387,6 +384,12 @@ ...@@ -387,6 +384,12 @@
<version>2.0</version> <version>2.0</version>
</dependency> </dependency>
<!-- util sdk -->
<dependency>
<groupId>com.dcg.sdk</groupId>
<artifactId>util-sdk</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
package com.pcloud.common.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* @author peidawei
* @version 1.0.0
* @package com.pcloud.common.entity
* @className BasePageRequestVO
* @description 分页请求VO基类
* @date 2018年11月29日 下午 14:46
*/
@ApiModel("分页请求VO基类")
public class BasePageRequestVO implements Serializable {
private static final long serialVersionUID = -4034188768789093041L;
@ApiModelProperty(hidden = true)
private Long userId;
@ApiModelProperty("每页多少条")
private Integer numPerPage;
@ApiModelProperty("当前页")
private Integer currentPage;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Integer getNumPerPage() {
return numPerPage;
}
public void setNumPerPage(Integer numPerPage) {
this.numPerPage = numPerPage;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
}
package com.pcloud.common.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* @author peidawei
* @version 1.0.0
* @package com.pcloud.common.entity
* @className BaseRequestVO
* @description 请求VO基类
* @date 2018年11月29日 下午 14:44
*/
@ApiModel("请求VO基类")
public class BaseRequestVO implements Serializable {
private static final long serialVersionUID = -1078697162056973900L;
@ApiModelProperty(hidden = true)
private Long userId;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
}
...@@ -54,7 +54,8 @@ public enum AppTypeEnum { ...@@ -54,7 +54,8 @@ public enum AppTypeEnum {
WISH("WISH"),// 愿望单 WISH("WISH"),// 愿望单
LIVEAPP("LIVEAPP"), //直播3.0 LIVEAPP("LIVEAPP"), //直播3.0
TASTETEST("TASTETEST"), //趣味测试 TASTETEST("TASTETEST"), //趣味测试
VIDEO_CLASSIC("VIDEO_CLASSIC"); //经典版视频 VIDEO_CLASSIC("VIDEO_CLASSIC"), //经典版视频
AUDIO_MAGIC("AUDIO_MAGIC"); //音频伴读魔法箱
/** /**
* 枚举转换 * 枚举转换
......
package com.pcloud.common.enums;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @author lily
* @date 2018/12/6 11:36
*/
public enum QrcodeTypeEnum {
MAGIC("AUDIO_MAGIC", 0, "听画书", "AUDIO_MAGIC", "APP", true),
REWARD("CLOCK", 1, "打卡书", "REWARD", "APP", true),
PREVIEW_APP("VIDEO", 2, "预习课", "PREVIEW", "APP", true),
PREVIEW_PRODUCT("VIDEO_SCHEDULE", 3, "预习课", "PREVIEW", "PRODUCT", true),
ZSCORE("ZSCORE", 4, "查分书", "ZSCORE", "APP", true);
/**
* 类型
*/
private String type;
private Integer value;
private String description;
private String scene;
private String typeCode;
private Boolean isNeedCover;
public static final Map<String, QrcodeTypeEnum> QRCODE_TYPE_MAP = new HashMap<>();
QrcodeTypeEnum(String type, Integer value, String description, String scene, String typeCode, Boolean isNeedCover) {
this.type = type;
this.value = value;
this.description = description;
this.scene = scene;
this.typeCode = typeCode;
this.isNeedCover = isNeedCover;
}
static {
Arrays.asList(values()).forEach((m) -> {
QRCODE_TYPE_MAP.put(m.type, m);
});
}
public String getType() {
return type;
}
public Integer getValue() {
return value;
}
public String getDescription() {
return description;
}
public String getScene() {
return scene;
}
public String getTypeCode() {
return typeCode;
}
public Boolean getNeedCover() {
return isNeedCover;
}
}
package com.pcloud.common.utils;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.pcloud.common.utils.validate.ValidateUtils;
/**
* 线程安全的时间工具类
* @author PENG
* @date 2018年12月11日16:40:06
*/
public class DateNewUtils extends org.apache.commons.lang.time.DateUtils {
public static final long DAY_MILLI = 24 * 60 * 60 * 1000;
public final static int LEFT_OPEN_RIGHT_OPEN = 1;
public final static int LEFT_CLOSE_RIGHT_OPEN = 2;
public final static int LEFT_OPEN_RIGHT_CLOSE = 3;
public final static int LEFT_CLOSE_RIGHT_CLOSE = 4;
/**
* 比较日期的模式 --只比较日期,不比较时间
*/
public final static int COMP_MODEL_DATE = 1;
/**
* 比较日期的模式 --只比较时间,不比较日期
*/
public final static int COMP_MODEL_TIME = 2;
/**
* 比较日期的模式 --比较日期,也比较时间
*/
public final static int COMP_MODEL_DATETIME = 3;
private static Logger logger = LoggerFactory.getLogger(DateNewUtils.class);
/**
* 要用到的DATE Format的定义
*/
public static final String SHORT_DATE_FORMAT_PATTERN = "yyyy-MM-dd";
public static final String YMD_DATE_FORMAT_PATTERN = "yyyyMMdd";
public static final String YMD_DATE_FORMAT_PATTERN1 = "yyyy/MM/dd";
public static final String YMD_DATE_FORMAT_PATTERN2 = "yyyy年MM月dd日";
public static final String LONG_DATE_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static final String TIME_WITH_MINUTE_PATTERN = "HH:mm";
public static final String TIME_DATE_FORMAT_PATTERN = "HH:mm:ss";
public static final String HMS_DATE_FORMAT_PATTERN = "HHmmss";
public static final String YMDHMS_DATE_FORMAT_PATTERN = "yyyyMMddHHmmss";
public static final String YMDHM_DATE_FORMAT_PATTERN = "yyyy-MM-dd HH:mm";
public static final String YMDHMSS_DATE_FORMAT_PATTERN = "yyyy-MM-dd hh:mm:ss:SSS";
/**
* 锁对象
*/
private static final Object LOCK_OBJ = new Object();
/**
* 存放不同的日期模板格式的sdf的Map
*/
private static Map<String, ThreadLocal<SimpleDateFormat>> sdfMap = new HashMap<>();
/**
* 返回一个ThreadLocal的sdf,每个线程只会new一次sdf
* @param pattern
* @return
*/
private static SimpleDateFormat getSdf(final String pattern) {
ThreadLocal<SimpleDateFormat> tl = sdfMap.get(pattern);
// 此处的双重判断和同步是为了防止sdfMap这个单例被多次put重复的sdf
if (tl == null) {
synchronized (LOCK_OBJ) {
// 这里是关键,使用ThreadLocal<SimpleDateFormat>替代原来直接new SimpleDateFormat
tl = sdfMap.computeIfAbsent(pattern, k -> ThreadLocal.withInitial(() -> new SimpleDateFormat(pattern)));
}
}
return tl.get();
}
/**
* 根据日期格式字符串解析日期字符串
* @param str 日期字符串
* @param parsePatterns 日期格式字符串
* @return 解析后日期
* @throws ParseException
*/
public static synchronized Date parseDate(String str, String parsePatterns) throws ParseException {
return org.apache.commons.lang.time.DateUtils.parseDate(str, new String[]{parsePatterns});
}
/**
* 根据单位字段比较两个日期
* @param date 日期1
* @param otherDate 日期2
* @param withUnit 单位字段,从Calendar field取值
* @return 等于返回0值, 大于返回大于0的值 小于返回小于0的值
*/
public static int compareDate(Date date, Date otherDate, int withUnit) {
Calendar dateCal = Calendar.getInstance();
dateCal.setTime(date);
Calendar otherDateCal = Calendar.getInstance();
otherDateCal.setTime(otherDate);
switch (withUnit) {
case Calendar.YEAR:
dateCal.clear(Calendar.MONTH);
otherDateCal.clear(Calendar.MONTH);
case Calendar.MONTH:
dateCal.set(Calendar.DATE, 1);
otherDateCal.set(Calendar.DATE, 1);
case Calendar.DATE:
dateCal.set(Calendar.HOUR_OF_DAY, 0);
otherDateCal.set(Calendar.HOUR_OF_DAY, 0);
case Calendar.HOUR:
dateCal.clear(Calendar.MINUTE);
otherDateCal.clear(Calendar.MINUTE);
case Calendar.MINUTE:
dateCal.clear(Calendar.SECOND);
otherDateCal.clear(Calendar.SECOND);
case Calendar.SECOND:
dateCal.clear(Calendar.MILLISECOND);
otherDateCal.clear(Calendar.MILLISECOND);
case Calendar.MILLISECOND:
break;
default:
throw new IllegalArgumentException("withUnit 单位字段 " + withUnit + " 不合法!!");
}
return dateCal.compareTo(otherDateCal);
}
/**
* 根据单位字段比较两个时间
* @param date 时间1
* @param otherDate 时间2
* @param withUnit 单位字段,从Calendar field取值
* @return 等于返回0值, 大于返回大于0的值 小于返回小于0的值
*/
public static int compareTime(Date date, Date otherDate, int withUnit) {
Calendar dateCal = Calendar.getInstance();
dateCal.setTime(date);
Calendar otherDateCal = Calendar.getInstance();
otherDateCal.setTime(otherDate);
dateCal.clear(Calendar.YEAR);
dateCal.clear(Calendar.MONTH);
dateCal.set(Calendar.DATE, 1);
otherDateCal.clear(Calendar.YEAR);
otherDateCal.clear(Calendar.MONTH);
otherDateCal.set(Calendar.DATE, 1);
switch (withUnit) {
case Calendar.HOUR:
dateCal.clear(Calendar.MINUTE);
otherDateCal.clear(Calendar.MINUTE);
case Calendar.MINUTE:
dateCal.clear(Calendar.SECOND);
otherDateCal.clear(Calendar.SECOND);
case Calendar.SECOND:
dateCal.clear(Calendar.MILLISECOND);
otherDateCal.clear(Calendar.MILLISECOND);
case Calendar.MILLISECOND:
break;
default:
throw new IllegalArgumentException("withUnit 单位字段 " + withUnit + " 不合法!!");
}
return dateCal.compareTo(otherDateCal);
}
/**
* 获得当前的日期毫秒
* @return
*/
public static long nowTimeMillis() {
return System.currentTimeMillis();
}
/**
* 获得当前的unix时间戳,不含毫秒
* @return
*/
public static long nowTimeSecond() {
return System.currentTimeMillis() / 1000;
}
/**
* 获得当前的unix时间戳,不含毫秒
* @return
*/
public static long addNowTimeSecond(long second) {
return System.currentTimeMillis() / 1000 + second;
}
/**
* 获得当前的时间戳
* @return
*/
public static Timestamp nowTimeStamp() {
return new Timestamp(nowTimeMillis());
}
/**
* yyyy-MM-dd 当前日期
*/
public static String getReqDate() {
return getSdf(YMD_DATE_FORMAT_PATTERN).format(new Date());
}
/**
* yyyy-MM-dd 传入日期
* @param date
* @return
*/
public static String getReqDate(Date date) {
return getSdf(SHORT_DATE_FORMAT_PATTERN).format(date);
}
/**
* yyyyMMdd 传入日期
* @param date
* @return
*/
public static String getReqDateyyyyMMdd(Date date) {
return getSdf(YMD_DATE_FORMAT_PATTERN).format(date);
}
/**
* yyyy-MM-dd 传入的时间戳
* @param tmp
* @return
*/
public static String timestampToDateStr(Timestamp tmp) {
return getSdf(SHORT_DATE_FORMAT_PATTERN).format(tmp);
}
/**
* HH:mm:ss 当前时间
* @return
*/
public static String getReqTime() {
return getSdf(TIME_DATE_FORMAT_PATTERN).format(new Date());
}
/**
* HHmmss 当前时间
* @return
*/
public static String getHmsTime() {
return getSdf(HMS_DATE_FORMAT_PATTERN).format(new Date());
}
/**
* yyyyMMddHHmmss 当前时间
* @return
*/
public static String getYmdHmsTime() {
return getSdf(YMDHMS_DATE_FORMAT_PATTERN).format(new Date());
}
/**
* 得到时间戳格式字串
* @param date
* @return
*/
public static String getTimeStampStr(Date date) {
return getSdf(LONG_DATE_FORMAT_PATTERN).format(date);
}
/**
* 得到长日期格式字串
* @return
*/
public static String getLongDateStr() {
return getSdf(LONG_DATE_FORMAT_PATTERN).format(new Date());
}
public static String getLongDateStr(Timestamp time) {
return getSdf(LONG_DATE_FORMAT_PATTERN).format(time);
}
/**
* 得到短日期格式字串
* @param date
* @return
*/
public static String getShortDateStr(Date date) {
return getSdf(SHORT_DATE_FORMAT_PATTERN).format(date);
}
public static String getShortDateStr() {
return getSdf(SHORT_DATE_FORMAT_PATTERN).format(new Date());
}
/**
* 计算 second 秒后的时间
* @param date
* @param second
* @return
*/
public static Date addSecond(Date date, int second) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.SECOND, second);
return calendar.getTime();
}
/**
* 计算 minute 分钟后的时间
* @param date
* @param minute
* @return
*/
public static Date addMinute(Date date, int minute) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, minute);
return calendar.getTime();
}
/**
* 计算 hour 小时后的时间
* @param date
* @param hour
* @return
*/
public static Date addHour(Date date, int hour) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR, hour);
return calendar.getTime();
}
/**
* 得到day的起始时间点。
* @param date
* @return
*/
public static Date getDayStart(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 得到day的终止时间点.
* @param date
* @return
*/
public static Date getDayEnd(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.add(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.MILLISECOND, -1);
return calendar.getTime();
}
/**
* 计算 day 天后的时间
* @param date
* @param day
* @return
*/
public static Date addDay(Date date, int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, day);
return calendar.getTime();
}
/**
* 得到month的终止时间点.
* @param date
* @return
*/
public static Date getMonthEnd(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.MILLISECOND, -1);
return calendar.getTime();
}
public static Date addYear(Date date, int year) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, 365 * year);
return calendar.getTime();
}
public static Timestamp strToTimestamp(String dateStr) {
return Timestamp.valueOf(dateStr);
}
public static Timestamp strToTimestamp(Date date) {
return Timestamp.valueOf(getSdf(LONG_DATE_FORMAT_PATTERN).format(date));
}
public static Timestamp getCurTimestamp() {
return Timestamp.valueOf(getSdf(LONG_DATE_FORMAT_PATTERN).format(new Date()));
}
/**
* 取得两个日期之间的日数
* @return t1到t2间的日数,如果t2 在 t1之后,返回正数,否则返回负数
*/
public static long daysBetween(java.sql.Timestamp t1, java.sql.Timestamp t2) {
return (t2.getTime() - t1.getTime()) / DAY_MILLI;
}
/**
* 返回java.sql.Timestamp型的SYSDATE
* @return java.sql.Timestamp型的SYSDATE
* @history
* @since 1.0
*/
public static java.sql.Timestamp getSysDateTimestamp() {
return new java.sql.Timestamp(System.currentTimeMillis());
}
/**
* 利用缺省的Date格式(YYYY/MM/DD)转换String到java.sql.Timestamp
* @param sDate Date string
* @return
* @history
* @since 1.0
*/
public static java.sql.Timestamp toSqlTimestamp(String sDate) {
if (sDate == null) {
return null;
}
if (sDate.length() != SHORT_DATE_FORMAT_PATTERN.length()
&& sDate.length() != LONG_DATE_FORMAT_PATTERN.length()) {
return null;
}
return toSqlTimestamp(sDate,
sDate.length() == SHORT_DATE_FORMAT_PATTERN.length() ? SHORT_DATE_FORMAT_PATTERN
: LONG_DATE_FORMAT_PATTERN);
}
/**
* 利用缺省的Date格式(YYYY/MM/DD hh:mm:ss)转化String到java.sql.Timestamp
* @param sDate Date string
* @param sFmt Date format YMD_DATE_FORMAT_PATTERN/TIME_DATE_FORMAT_PATTERN
* @return
* @history
* @since 1.0
*/
public static java.sql.Timestamp toSqlTimestamp(String sDate, String sFmt) {
String temp = null;
if (sDate == null || sFmt == null) {
return null;
}
if (sDate.length() != sFmt.length()) {
return null;
}
if (sFmt.equals(LONG_DATE_FORMAT_PATTERN)) {
temp = sDate.replace('/', '-');
temp = temp + ".000000000";
} else if (sFmt.equals(SHORT_DATE_FORMAT_PATTERN)) {
temp = sDate.replace('/', '-');
temp = temp + " 00:00:00.000000000";
} else {
return null;
}
return java.sql.Timestamp.valueOf(temp);
}
/**
* 以YYYY/MM/DD HH24:MI:SS格式返回系统日期时间
* @return 系统日期时间
* @history
* @since 1.0
*/
public static String getSysDateTimeString() {
return toString(new java.util.Date(System.currentTimeMillis()), getSdf(LONG_DATE_FORMAT_PATTERN));
}
/**
* 根据指定的Format转化java.util.Date到String
* @param dt java.util.Date instance
* @param sFmt Date format , YMD_DATE_FORMAT_PATTERN or TIME_DATE_FORMAT_PATTERN
* @return
* @history
* @since 1.0
*/
public static String toString(java.util.Date dt, String sFmt) {
if (dt == null || sFmt == null || "".equals(sFmt)) {
return "";
}
return toString(dt, getSdf(sFmt));
}
/**
* 利用指定SimpleDateFormat instance转换java.util.Date到String
* @param dt java.util.Date instance
* @param formatter SimpleDateFormat Instance
* @return
* @history
* @since 1.0
*/
private static String toString(java.util.Date dt, SimpleDateFormat formatter) {
String sRet = null;
try {
sRet = formatter.format(dt);
} catch (Exception e) {
logger.error("error:", e);
sRet = null;
}
return sRet;
}
/**
* 转换java.sql.Timestamp到String,格式为YYYY/MM/DD HH24:MI
* @param dt java.sql.Timestamp instance
* @return
* @history
* @since 1.0
*/
public static String toSqlTimestampString2(java.sql.Timestamp dt) {
if (dt == null) {
return null;
}
String temp = toSqlTimestampString(dt, LONG_DATE_FORMAT_PATTERN);
return temp.substring(0, 16);
}
public static String toString(java.sql.Timestamp dt) {
return dt == null ? "" : toSqlTimestampString2(dt);
}
/**
* 根据指定的格式转换java.sql.Timestamp到String
* @param dt java.sql.Timestamp instance
* @param sFmt Date 格式,YMD_DATE_FORMAT_PATTERN/TIME_DATE_FORMAT_PATTERN/
* DATE_FORMAT_SESSION
* @return
* @history
* @since 1.0
*/
public static String toSqlTimestampString(java.sql.Timestamp dt, String sFmt) {
String temp = null;
String out = null;
if (dt == null || sFmt == null) {
return null;
}
temp = dt.toString();
if (sFmt.equals(LONG_DATE_FORMAT_PATTERN) || sFmt.equals(SHORT_DATE_FORMAT_PATTERN)) {
temp = temp.substring(0, sFmt.length());
out = temp.replace('/', '-');
}
return out;
}
/**
* 得到当前日期的星期
* @return
*/
public static int getWeek() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* Timestamp 格式转换成yyyy-MM-dd timestampToSql(Timestamp 格式转换成yyyy-MM-dd)
* @param timestamp 时间
* @return createTimeStr yyyy-MM-dd 时间
* @Exception 异常对象
* @since V1.0
*/
public static String timestampToStringYMD(java.sql.Timestamp timestamp) {
return getSdf(SHORT_DATE_FORMAT_PATTERN).format(timestamp);
}
/**
* 判断一个时间是否在某个时间区间内
* @param now 目标时间
* @param start 时间区间开始
* @param end 时间区间结束
* @param model 区间模式
* @return 是否在区间内
*/
public static boolean isBetween(Date now, Date start, Date end, int model) {
return isBetween(now, start, end, model, COMP_MODEL_DATE);
}
/**
* 判断时间是否在制定的时间段之类
* @param date 需要判断的时间
* @param start 时间段的起始时间
* @param end 时间段的截止时间
* @param interModel 区间的模式
* 取值:
* LEFT_OPEN_RIGHT_OPEN
* LEFT_CLOSE_RIGHT_OPEN
* LEFT_OPEN_RIGHT_CLOSE
* LEFT_CLOSE_RIGHT_CLOSE
* @param compModel 比较的模式
* 取值:
* COMP_MODEL_DATE 只比较日期,不比较时间
* COMP_MODEL_TIME 只比较时间,不比较日期
* COMP_MODEL_DATETIME 比较日期,也比较时间
* @return
*/
public static boolean isBetween(Date date, Date start, Date end, int interModel, int compModel) {
if (date == null || start == null || end == null) {
throw new IllegalArgumentException("日期不能为空");
}
SimpleDateFormat format = null;
switch (compModel) {
case COMP_MODEL_DATE: {
format = getSdf(YMD_DATE_FORMAT_PATTERN);
break;
}
case COMP_MODEL_TIME: {
format = getSdf(HMS_DATE_FORMAT_PATTERN);
break;
}
case COMP_MODEL_DATETIME: {
format = getSdf(YMDHMS_DATE_FORMAT_PATTERN);
break;
}
default: {
throw new IllegalArgumentException(String.format("日期的比较模式[%d]有误", compModel));
}
}
long dateNumber = Long.parseLong(format.format(date));
long startNumber = Long.parseLong(format.format(start));
long endNumber = Long.parseLong(format.format(end));
switch (interModel) {
case LEFT_OPEN_RIGHT_OPEN: {
if (dateNumber <= startNumber || dateNumber >= endNumber) {
return false;
} else {
return true;
}
}
case LEFT_CLOSE_RIGHT_OPEN: {
if (dateNumber < startNumber || dateNumber >= endNumber) {
return false;
} else {
return true;
}
}
case LEFT_OPEN_RIGHT_CLOSE: {
if (dateNumber <= startNumber || dateNumber > endNumber) {
return false;
} else {
return true;
}
}
case LEFT_CLOSE_RIGHT_CLOSE: {
if (dateNumber < startNumber || dateNumber > endNumber) {
return false;
} else {
return true;
}
}
default: {
throw new IllegalArgumentException(String.format("日期的区间模式[%d]有误", interModel));
}
}
}
/**
* 得到当前周起始时间
* @param date
* @return
*/
public static Date getWeekStart(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.get(Calendar.WEEK_OF_YEAR);
int firstDay = calendar.getFirstDayOfWeek();
calendar.set(Calendar.DAY_OF_WEEK, firstDay);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 得到当前周截止时间
* @param date
* @return
*/
public static Date getWeekEnd(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.get(Calendar.WEEK_OF_YEAR);
int firstDay = calendar.getFirstDayOfWeek();
calendar.set(Calendar.DAY_OF_WEEK, 8 - firstDay);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 得到当月起始时间
* @param date
* @return
*/
public static Date getMonthStart(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 得到当前年起始时间
* @param date
* @return
*/
public static Date getYearStart(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 得到当前年最后一天
* @param date
* @return
*/
public static Date getYearEnd(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 31);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 取得月天数
* @param date
* @return
*/
public static int getDayOfMonth(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* 取得月第一天
* @param date
* @return
*/
public static Date getFirstDateOfMonth(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));
return c.getTime();
}
/**
* 取得月最后一天
* @param date
* @return
*/
public static Date getLastDateOfMonth(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
return c.getTime();
}
/**
* 取得季度第一天
* @param date
* @return
*/
public static Date getSeasonStart(Date date) {
return getDayStart(getFirstDateOfMonth(getSeasonDate(date)[0]));
}
/**
* 取得季度最后一天
* @param date
* @return
*/
public static Date getSeasonEnd(Date date) {
return getDayEnd(getLastDateOfMonth(getSeasonDate(date)[2]));
}
/**
* 取得季度月
* @param date
* @return
*/
public static Date[] getSeasonDate(Date date) {
Date[] season = new Date[3];
Calendar c = Calendar.getInstance();
c.setTime(date);
int nSeason = getSeason(date);
if (nSeason == 1) {// 第一季度
c.set(Calendar.MONTH, Calendar.JANUARY);
season[0] = c.getTime();
c.set(Calendar.MONTH, Calendar.FEBRUARY);
season[1] = c.getTime();
c.set(Calendar.MONTH, Calendar.MARCH);
season[2] = c.getTime();
} else if (nSeason == 2) {// 第二季度
c.set(Calendar.MONTH, Calendar.APRIL);
season[0] = c.getTime();
c.set(Calendar.MONTH, Calendar.MAY);
season[1] = c.getTime();
c.set(Calendar.MONTH, Calendar.JUNE);
season[2] = c.getTime();
} else if (nSeason == 3) {// 第三季度
c.set(Calendar.MONTH, Calendar.JULY);
season[0] = c.getTime();
c.set(Calendar.MONTH, Calendar.AUGUST);
season[1] = c.getTime();
c.set(Calendar.MONTH, Calendar.SEPTEMBER);
season[2] = c.getTime();
} else if (nSeason == 4) {// 第四季度
c.set(Calendar.MONTH, Calendar.OCTOBER);
season[0] = c.getTime();
c.set(Calendar.MONTH, Calendar.NOVEMBER);
season[1] = c.getTime();
c.set(Calendar.MONTH, Calendar.DECEMBER);
season[2] = c.getTime();
}
return season;
}
/**
* 1 第一季度 2 第二季度 3 第三季度 4 第四季度
* @param date
* @return
*/
public static int getSeason(Date date) {
int season = 0;
Calendar c = Calendar.getInstance();
c.setTime(date);
int month = c.get(Calendar.MONTH);
switch (month) {
case Calendar.JANUARY:
case Calendar.FEBRUARY:
case Calendar.MARCH:
season = 1;
break;
case Calendar.APRIL:
case Calendar.MAY:
case Calendar.JUNE:
season = 2;
break;
case Calendar.JULY:
case Calendar.AUGUST:
case Calendar.SEPTEMBER:
season = 3;
break;
case Calendar.OCTOBER:
case Calendar.NOVEMBER:
case Calendar.DECEMBER:
season = 4;
break;
default:
break;
}
return season;
}
/**
* 字符串转date
* @param dateString
* @return
*/
public static Date stringToDate(String dateString) {
Date date = null;
try {
date = getSdf(YMD_DATE_FORMAT_PATTERN1).parse(dateString);
} catch (ParseException e) {
logger.error("error:", e);
}
return date;
}
/**
* 字符串转date
* @param dateString
* @return
*/
public static Date stringToShortDate(String dateString) {
Date date = null;
try {
date = getSdf(SHORT_DATE_FORMAT_PATTERN).parse(dateString);
} catch (ParseException e) {
logger.error("error:", e);
}
return date;
}
/**
* 字符串转换datetime
* @param dateString
* @return
*/
public static Date stringToDateTime(String dateString) {
Date date = null;
try {
date = getSdf(LONG_DATE_FORMAT_PATTERN).parse(dateString);
} catch (ParseException e) {
logger.error("error:", e);
}
return date;
}
/**
* 判断输入日期是一个星期中的第几天(星期天为一个星期第一天)
* @param date
* @return
*/
public static int getWeekIndex(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK);
}
/**
* 当前时间的前几天,并且以例如2013/12/09 00:00:00 形式输出
*/
public static Date subDays(int days) {
Date date = addDay(new Date(), -days);
String dateStr = getReqDate(date);
Date date1 = null;
try {
date1 = getSdf(SHORT_DATE_FORMAT_PATTERN).parse(dateStr);
} catch (ParseException e) {
logger.error("error:", e);
}
return date1;
}
/**
* 判断开始时间和结束时间,是否超出了当前时间的一定的间隔数限制 如:开始时间和结束时间,不能超出距离当前时间90天
* @param startDate 开始时间
* @param endDate 结束时间按
* @param interval 间隔数
* @param dateUnit 单位(如:月,日),参照Calendar的时间单位
* @return
*/
public static boolean isOverIntervalLimit(Date startDate, Date endDate, int interval, int dateUnit) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(dateUnit, interval * (-1));
Date curDate = getDayStart(cal.getTime());
if (getDayStart(startDate).compareTo(curDate) < 0 || getDayStart(endDate).compareTo(curDate) < 0) {
return true;
}
return false;
}
/**
* 判断开始时间和结束时间,是否超出了当前时间的一定的间隔数限制, 时间单位默认为天数 如:开始时间和结束时间,不能超出距离当前时间90天
* @param startDate 开始时间
* @param endDate 结束时间按
* @param interval 间隔数
* @return
*/
public static boolean isOverIntervalLimit(Date startDate, Date endDate, int interval) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DAY_OF_MONTH, interval * (-1));
Date curDate = getDayStart(cal.getTime());
if (getDayStart(startDate).compareTo(curDate) < 0 || getDayStart(endDate).compareTo(curDate) < 0) {
return true;
}
return false;
}
/**
* 判断开始时间和结束时间,是否超出了当前时间的一定的间隔数限制, 时间单位默认为天数 如:开始时间和结束时间,不能超出距离当前时间90天
* @param startDateStr 开始时间
* @param endDateStr 结束时间按
* @param interval 间隔数
* @return
*/
public static boolean isOverIntervalLimit(String startDateStr, String endDateStr, int interval) {
Date startDate = null;
Date endDate = null;
try {
startDate = parseDate(startDateStr, SHORT_DATE_FORMAT_PATTERN);
endDate = parseDate(endDateStr, SHORT_DATE_FORMAT_PATTERN);
} catch (ParseException e) {
logger.error("error:", e);
return false;
}
return isOverIntervalLimit(startDate, endDate, interval);
}
/**
* 传入时间字符串及时间格式,返回对应的Date对象
* @param src 时间字符串
* @param pattern 时间格式
* @return Date
*/
public static Date getDateFromString(String src, String pattern) {
try {
return getSdf(pattern).parse(src);
} catch (ParseException e) {
logger.error("error:", e);
return null;
}
}
/**
* 取季度
* @param date
* @return
*/
@SuppressWarnings("deprecation")
public static int getQuarter(Date date) {
if (date.getMonth() == 0 || date.getMonth() == 1 || date.getMonth() == 2) {
return 1;
} else if (date.getMonth() == 3 || date.getMonth() == 4 || date.getMonth() == 5) {
return 2;
} else if (date.getMonth() == 6 || date.getMonth() == 7 || date.getMonth() == 8) {
return 3;
} else if (date.getMonth() == 9 || date.getMonth() == 10 || date.getMonth() == 11) {
return 4;
} else {
return 0;
}
}
/**
* 取得通用日期时间格式字符串
* @param date
* @return String
*/
public static String formatDate(Date date) {
if (date == null) {
return "";
}
return getSdf(LONG_DATE_FORMAT_PATTERN).format(date);
}
/**
* 获取当日的日期格式串
* @return String
*/
public static String today() {
return formatDate(new Date(), SHORT_DATE_FORMAT_PATTERN);
}
/**
* 获取当前时间格式串
* @return String
*/
public static String currentTime() {
return formatDate(new Date(), YMDHMSS_DATE_FORMAT_PATTERN);
}
/**
* 取得指定日期格式的字符串
* @param date
* @return pattern
*/
public static String formatDate(Date date, String pattern) {
return getSdf(pattern).format(date);
}
/**
* 获取昨日的日期格式串
* @return Date
*/
public static String getYesterday() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
return formatDate(calendar.getTime(), SHORT_DATE_FORMAT_PATTERN);
}
/**
* 判断当前时间是否在一定的时间范围内
* @param startTime
* @return boolean
*/
public static boolean isInBetweenTimes(String startTime, String endTime) {
Date nowTime = new Date();
String time = getSdf(TIME_DATE_FORMAT_PATTERN).format(nowTime);
if (time.compareTo(startTime) >= 0 && time.compareTo(endTime) <= 0) {
return true;
} else {
return false;
}
}
/**
* 判断当前日期是否在一定的时间范围内
* @param startDate
* @param endDate
* @return
*/
public static boolean isInBetweenDate(String startDate, String endDate) {
Date now = new Date();
String date = getSdf(SHORT_DATE_FORMAT_PATTERN).format(now);
if (date.compareTo(startDate) >= 0 && date.compareTo(endDate) <= 0) {
return true;
} else {
return false;
}
}
/**
* 判断当前日期是否在一定的时间范围内
* @param startDate
* @param endDate
* @return
*/
public static boolean isInBetweenDate(Date startDate, Date endDate) {
Date now = new Date();
String date = getSdf(SHORT_DATE_FORMAT_PATTERN).format(now);
if (date.compareTo(getSdf(SHORT_DATE_FORMAT_PATTERN).format(startDate)) >= 0
&& date.compareTo(getSdf(SHORT_DATE_FORMAT_PATTERN).format(endDate)) <= 0) {
return true;
} else {
return false;
}
}
/**
* 字符转日期
* @param dateStr
* @return
*/
public static Date getDateByStr(String dateStr) {
SimpleDateFormat formatter = null;
if (dateStr == null) {
return null;
} else if (dateStr.length() == 10) {
formatter = getSdf(SHORT_DATE_FORMAT_PATTERN);
} else if (dateStr.length() == 16) {
formatter = getSdf(YMDHM_DATE_FORMAT_PATTERN);
} else if (dateStr.length() == 19) {
formatter = getSdf(LONG_DATE_FORMAT_PATTERN);
} else if (dateStr.length() > 19) {
dateStr = dateStr.substring(0, 19);
formatter = getSdf(LONG_DATE_FORMAT_PATTERN);
} else {
return null;
}
try {
return formatter.parse(dateStr);
} catch (ParseException e) {
logger.error("error:", e);
return null;
}
}
/**
* 根据传入的数字,输出相比现在days天的数据
* @param days
* @return Date
*/
public static Date getDate(int days) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, days);
return calendar.getTime();
}
/**
* 根据传入的数字,输出相比现在days天的数据
* @param days
* @return Date
*/
public static Date getDate(String currentDate, int days) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, days);
return calendar.getTime();
}
/**
* 日期最大时间
* @param dt
* @return
*/
public static Date getMaxTime(Date dt) {
Date dt1 = null;
Calendar ca = Calendar.getInstance();
ca.setTime(dt);
ca.add(Calendar.DAY_OF_MONTH, 1);
dt1 = ca.getTime();
dt1 = getMinTime(dt1);
ca.setTime(dt1);
ca.add(Calendar.SECOND, -1);
dt1 = ca.getTime();
return dt1;
}
/**
* 日期最小时间
* @param dt
* @return
*/
public static Date getMinTime(Date dt) {
return getDateByStr(formatDate(dt, SHORT_DATE_FORMAT_PATTERN));
}
/**
* 月的最后一天
* @param date
* @return
*/
@SuppressWarnings("deprecation")
public static Date getLastDayOfMonth(Date date) {
Calendar cDay1 = Calendar.getInstance();
cDay1.setTime(date);
int lastDay = cDay1.getActualMaximum(Calendar.DAY_OF_MONTH);
Date lastDate = cDay1.getTime();
lastDate.setDate(lastDay);
return lastDate;
}
/**
* 月的第一天
* @param date
* @return
*/
public static Date getFirstDayOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DATE));
return calendar.getTime();
}
/**
* 上月第一天
* @return
*/
public static Date getPreviousMonthFirstDay() {
Calendar lastDate = Calendar.getInstance();
// 设为当前月的1号
lastDate.set(Calendar.DATE, 1);
// 减一个月,变为下月的1号
lastDate.add(Calendar.MONTH, -1);
return getMinTime(lastDate.getTime());
}
/**
* 上月最后一天
* @return
*/
public static Date getPreviousMonthLastDay() {
Calendar lastDate = Calendar.getInstance();
// 设为当前月的1号
lastDate.set(Calendar.DATE, 1);
lastDate.add(Calendar.DATE, -1);
return getMinTime(lastDate.getTime());
}
/**
* 两个日期相关天数
* @param startDate
* @param endDate
* @return
*/
public static long getDateDiff(String startDate, String endDate) {
long diff = 0;
try {
Date date1 = getSdf(SHORT_DATE_FORMAT_PATTERN).parse(startDate);
Date date2 = getSdf(SHORT_DATE_FORMAT_PATTERN).parse(endDate);
diff = (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000) > 0
? (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000)
: (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000);
} catch (ParseException e) {
logger.error("error:", e);
}
return diff;
}
public static long getDateDiff(Date date1, Date date2) {
if (ValidateUtils.isEmpty(date1) || ValidateUtils.isEmpty(date1)) {
return 0L;
}
long diff = (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000) > 0
? (date1.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000)
: (date2.getTime() - date1.getTime()) / (24 * 60 * 60 * 1000);
return diff;
}
/**
* 判断两个时间是不是在一个周中
*/
public static boolean isSameWeekWithToday(Date date) {
if (date == null) {
return false;
}
// 0.先把Date类型的对象转换Calendar类型的对象
Calendar todayCal = Calendar.getInstance();
Calendar dateCal = Calendar.getInstance();
todayCal.setTime(new Date());
dateCal.setTime(date);
int subYear = todayCal.get(Calendar.YEAR) - dateCal.get(Calendar.YEAR);
// subYear==0,说明是同一年
if (subYear == 0) {
if (todayCal.get(Calendar.WEEK_OF_YEAR) == dateCal.get(Calendar.WEEK_OF_YEAR)) {
return true;
}
} else if (subYear == 1 && dateCal.get(Calendar.MONTH) == 11 && todayCal.get(Calendar.MONTH) == 0) {
if (todayCal.get(Calendar.WEEK_OF_YEAR) == dateCal.get(Calendar.WEEK_OF_YEAR)) {
return true;
}
} else if (subYear == -1 && todayCal.get(Calendar.MONTH) == 11 && dateCal.get(Calendar.MONTH) == 0) {
if (todayCal.get(Calendar.WEEK_OF_YEAR) == dateCal.get(Calendar.WEEK_OF_YEAR)) {
return true;
}
}
return false;
}
/**
* getStrFormTime: <br/>
* @param form 格式时间
* @param date 时间
* @return
*/
public static String getStrFormTime(String form, Date date) {
return getSdf(form).format(date);
}
/**
* 获取几天内日期 return 2014-5-4、2014-5-3
*/
public static List<String> getLastDays(int countDay) {
List<String> listDate = new ArrayList<>();
for (int i = 0; i < countDay; i++) {
listDate.add(getReqDateyyyyMMdd(getDate(-i)));
}
return listDate;
}
/**
* 获取几天内日期 return 2014-5-4、2014-5-3
*/
public static List<String> getLastDays(String currentDate, int countDay) {
Date date = stringToShortDate(currentDate);
List<String> listDate = new ArrayList<>();
for (int i = 0; i < countDay; i++) {
listDate.add(getReqDate(addDay(date, -i)));
}
return listDate;
}
/**
* 对时间进行格式化
* @param date
* @return
*/
public static Date dateFormat(Date date) {
SimpleDateFormat sdf = getSdf(SHORT_DATE_FORMAT_PATTERN);
Date value = new Date();
try {
value = sdf.parse(sdf.format(date));
} catch (ParseException e) {
logger.error("error:", e);
}
return value;
}
/**
* 比较两个时间差
* @param endDate
* @param nowDate
* @return
*/
public static String datePoor(Date endDate, Date nowDate) {
if (endDate == null || nowDate == null) {
return null;
}
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - nowDate.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
return String.valueOf(day) + "天" + hour + "小时" + min + "分钟";
}
/**
* 获取两个时间差,时,分,秒
* @param endDate
* @param nowDate
* @return
*/
public static long[] getDatePoor(Date endDate, Date nowDate) {
if (endDate == null || nowDate == null) {
return null;
}
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - nowDate.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
return new long[]{day, hour, min};
}
/**
* 获取下一周最后一天
* @return
*/
public static Date getLastDayOfNextWeek() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.WEEK_OF_YEAR, 1);
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
calendar.add(Calendar.DATE, 1);
}
return calendar.getTime();
}
/**
* 获取今天开始时间
* @return
*/
public static Date getDayBegin() {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
* 获取今天结束时间
* @return
*/
public static Date getDayEnd() {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}
/**
* 获取某个日期的开始时间
* @param day
* @return
*/
public static Timestamp getDayStartTime(Date day) {
Calendar calendar = Calendar.getInstance();
if (null != day) {
calendar.setTime(day);
}
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
calendar.set(Calendar.MILLISECOND, 0);
return new Timestamp(calendar.getTimeInMillis());
}
/**
* 获取某个日期的结束时间
* @param day 日期
* @return
*/
public static Timestamp getDayEndTime(Date day) {
Calendar calendar = Calendar.getInstance();
if (null != day) {
calendar.setTime(day);
}
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
calendar.set(Calendar.MILLISECOND, 999);
return new Timestamp(calendar.getTimeInMillis());
}
/**
* 获取昨天开始时间
* @return
*/
public static Date getBeginDayOfYesterday() {
Calendar cal = new GregorianCalendar();
cal.setTime(getDayBegin());
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
/**
* 获取昨天的结束时间
* @return
*/
public static Date getEndDayOfYesterDay() {
Calendar cal = new GregorianCalendar();
cal.setTime(getDayEnd());
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
}
package com.pcloud.common.utils; package com.pcloud.common.utils;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.pcloud.common.constant.AliyunConstant; import com.pcloud.common.constant.AliyunConstant;
import com.pcloud.common.constant.FilePathConst; import com.pcloud.common.constant.FilePathConst;
import com.pcloud.common.constant.OSConstant; import com.pcloud.common.constant.OSConstant;
import com.pcloud.common.entity.UploadResultInfo; import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.exceptions.BizException; import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException; import com.pcloud.common.exceptions.FileException;
import com.pcloud.common.utils.aliyun.OssUtils; import com.pcloud.common.utils.aliyun.OssUtils;
import com.pcloud.common.utils.encode.CpdetectorEncoding; import com.pcloud.common.utils.encode.CpdetectorEncoding;
import com.pcloud.common.utils.string.StringTools; import com.pcloud.common.utils.string.StringTools;
import com.pcloud.common.utils.string.StringUtil; import com.pcloud.common.utils.string.StringUtil;
import it.sauronsoftware.jave.AudioAttributes; import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder; import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException; import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes; import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException; import it.sauronsoftware.jave.InputFormatException;
/** /**
* @描述:文件工具类. @作者:DiSeng.H * @描述:文件工具类. @作者:DiSeng.H
* @创建时间:2016年3月10日,上午11:56:26 @版本:1.0 * @创建时间:2016年3月10日,上午11:56:26 @版本:1.0
*/ */
public class FileUtils { public class FileUtils {
/** /**
* logger * logger
*/ */
private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class); private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
/** /**
* PDF * PDF
*/ */
public final static String PDF = "PDF"; public final static String PDF = "PDF";
/** /**
* XML * XML
*/ */
public final static String XML = "XML"; public final static String XML = "XML";
/** /**
* IMAGE * IMAGE
*/ */
public final static String IMAGE = "IMAGE"; public final static String IMAGE = "IMAGE";
/** /**
* 音频 * 音频
*/ */
public final static String AUDIO = "AUDIO"; public final static String AUDIO = "AUDIO";
/** /**
* 视频格式 * 视频格式
*/ */
public final static String VIDEO = "VIDEO"; public final static String VIDEO = "VIDEO";
/** /**
* 压缩格式 * 压缩格式
*/ */
public final static String COMPRESS = "COMPRESS"; public final static String COMPRESS = "COMPRESS";
/** /**
* 办公软件 * 办公软件
*/ */
public final static String EDITOR = "EDITOR"; public final static String EDITOR = "EDITOR";
/** /**
* 文本格式 * 文本格式
*/ */
public final static String TEXT = "TEXT"; public final static String TEXT = "TEXT";
/** /**
* PDF文件格式 * OFFICE
*/ */
public static final String[] PDF_GATHER = {"PDF"}; public final static String OFFICE = "OFFICE";
/** /**
* XML文件格式 * PDF文件格式
*/ */
public static final String[] XML_GATHER = {"XML"}; public static final String[] PDF_GATHER = { "PDF" };
/** /**
* 图片文件格式 * XML文件格式
*/ */
public static final String[] IMAGE_GATHER = {"BMP", "JPG", "GIF", "PNG", "PCX", "TIF", "JPEG", "SVG"}; public static final String[] XML_GATHER = { "XML" };
/** /**
* 音頻文件格式 【"LRC" 为歌词字幕(这里作为音頻文件上传)】 * 图片文件格式
*/ */
public static final String[] AUDIO_GATHER = {"AMR", "MP3", "WMA", "WAV", "AAC", "APE", "M4A"}; public static final String[] IMAGE_GATHER = { "BMP", "JPG", "GIF", "PNG", "PCX", "TIF", "JPEG", "SVG", "WEBP" };
/** /**
* 視頻文件格式 【"SRT", "SSA", "SMI", "SUB" 为视频“外挂型”字幕(这里作为视频文件上传)】 * 音頻文件格式 【"LRC" 为歌词字幕(这里作为音頻文件上传)】
*/ */
public static final String[] VIDEO_GATHER = {"MPG", "MPEG", "AVI", "MOV", "ASF", "WMV", "NAVI", "3GP", "MKV", public static final String[] AUDIO_GATHER = { "AMR", "MP3", "WMA", "WAV", "AAC", "APE", "M4A" };
"FLV", "F4V", "RMVB", "RM", "MP4", "SRT", "SSA", "SMI", "SUB", "ASX", "M3U8"};
/**
/** * 視頻文件格式 【"SRT", "SSA", "SMI", "SUB" 为视频“外挂型”字幕(这里作为视频文件上传)】
* 压缩包文件格式 */
*/ public static final String[] VIDEO_GATHER = { "MPG", "MPEG", "AVI", "MOV", "ASF", "WMV", "NAVI", "3GP", "MKV",
public static final String[] COMPRESS_GATHER = {"RAR", "ZIP"}; "FLV", "F4V", "RMVB", "RM", "MP4", "SRT", "SSA", "SMI", "SUB", "ASX", "M3U8" };
/** /**
* 文件格式 * 压缩包文件格式
*/ */
public static final String[] TEXT_GATHER = {"TXT", "LRC"}; public static final String[] COMPRESS_GATHER = { "RAR", "ZIP" };
/** /**
* 编辑器格式 * 文件格式
*/ */
public static final String[] EDITOR_GATHER = {"DOC", "DOCX", "XLS", "XLSX", "PPT", "PPTX"}; public static final String[] TEXT_GATHER = { "TXT", "LRC" };
/** /**
* word格式 * 编辑器格式
*/ */
public static final String[] WORD_GATHER = {"DOC", "DOCX"}; public static final String[] EDITOR_GATHER = { "DOC", "DOCX", "XLS", "XLSX", "PPT", "PPTX" };
/** /**
* excel格式 * word格式
*/ */
public static final String[] EXCEL_GATHER = {"XLS", "XLSX", "XLSM", "XLT", "XLTX", "XLTM", "CSV"}; public static final String[] WORD_GATHER = { "DOC", "DOCX" };
/** /**
* PPT格式 * excel格式
*/ */
public static final String[] PPT_GATHER = {"PPT", "PPTX"}; public static final String[] EXCEL_GATHER = { "XLS", "XLSX", "XLSM", "XLT", "XLTX", "XLTM", "CSV" };
/** /**
* 根据文件类型获取文件分类 * PPT格式
* */
* @param fileType public static final String[] PPT_GATHER = { "PPT", "PPTX" };
* @return
*/ /**
public static String getGatherName(String fileType) { * office
if (StringUtil.isEmpty(fileType)) { */
return null; public static final String[] OFFICE_GATHER = { "DOC", "DOCX", "PPT", "PPTX", "XLS", "XLSX", "XLSM", "XLT", "XLTX",
} "XLTM", "CSV" };
// IMAGE
if (Arrays.asList(IMAGE_GATHER).contains(fileType.toUpperCase())) { /**
return IMAGE; * 根据文件类型获取文件分类
} *
// AUDIO * @param fileType
if (Arrays.asList(AUDIO_GATHER).contains(fileType.toUpperCase())) { * @return
return AUDIO; */
} public static String getGatherName(String fileType) {
// VIDEO if (StringUtil.isEmpty(fileType)) {
if (Arrays.asList(VIDEO_GATHER).contains(fileType.toUpperCase())) { return null;
return VIDEO; }
} // IMAGE
// PDF if (Arrays.asList(IMAGE_GATHER).contains(fileType.toUpperCase())) {
if (Arrays.asList(PDF_GATHER).contains(fileType.toUpperCase())) { return IMAGE;
return PDF; }
} // AUDIO
// XML if (Arrays.asList(AUDIO_GATHER).contains(fileType.toUpperCase())) {
if (Arrays.asList(XML_GATHER).contains(fileType.toUpperCase())) { return AUDIO;
return XML; }
} // VIDEO
// COMPRESS if (Arrays.asList(VIDEO_GATHER).contains(fileType.toUpperCase())) {
if (Arrays.asList(COMPRESS_GATHER).contains(fileType.toUpperCase())) { return VIDEO;
return COMPRESS; }
} // PDF
// EDITOR if (Arrays.asList(PDF_GATHER).contains(fileType.toUpperCase())) {
if (Arrays.asList(EDITOR_GATHER).contains(fileType.toUpperCase())) { return PDF;
return EDITOR; }
} // XML
// COMPRESS if (Arrays.asList(XML_GATHER).contains(fileType.toUpperCase())) {
if (Arrays.asList(TEXT_GATHER).contains(fileType.toUpperCase())) { return XML;
return TEXT; }
} // COMPRESS
return null; if (Arrays.asList(COMPRESS_GATHER).contains(fileType.toUpperCase())) {
} return COMPRESS;
}
/** // EDITOR
* 传入文件夹路径,该方法能够实现创建整个路径 if (Arrays.asList(EDITOR_GATHER).contains(fileType.toUpperCase())) {
* return EDITOR;
* @param path 文件夹路径,不包含文件名称及后缀名 }
*/ // TEXT
public static boolean isDir(String filePath) { if (Arrays.asList(TEXT_GATHER).contains(fileType.toUpperCase())) {
if (StringUtil.isEmpty(filePath)) { return TEXT;
return false; }
} // OFFICE
String[] paths = filePath.split("/"); if (Arrays.asList(OFFICE_GATHER).contains(fileType.toUpperCase())) {
String temp = ""; return OFFICE;
for (int i = 0; i < paths.length; i++) { }
if (i == 0) { return null;
temp = paths[0]; }
} else {
temp += "/" + paths[i]; /**
} * 传入文件夹路径,该方法能够实现创建整个路径
creatDir(temp); *
} * @param path
return true; * 文件夹路径,不包含文件名称及后缀名
} */
public static boolean isDir(String filePath) {
/** if (StringUtil.isEmpty(filePath)) {
* 该方法用来判断文件是否存在,如果不存在则创建 return false;
* }
* @param filePath String[] paths = filePath.split("/");
*/ String temp = "";
public static boolean creatFile(String filePath) { for (int i = 0; i < paths.length; i++) {
if (StringUtil.isEmpty(filePath)) { if (i == 0) {
return false; temp = paths[0];
} } else {
File file = new File(filePath); temp += "/" + paths[i];
if (!file.exists()) { }
try { creatDir(temp);
file.createNewFile(); }
return true; return true;
} catch (Exception e) { }
LOGGER.error("【文件工具】创建文件失败,<ERROR>:" + e.getMessage(), e);
} /**
} * 该方法用来判断文件是否存在,如果不存在则创建
return false; *
} * @param filePath
*/
/** public static boolean creatFile(String filePath) {
* 该方法用来判断文件是否存在,如果不存在则创建,该方法能够实现创建整个路径 if (StringUtil.isEmpty(filePath)) {
* return false;
* @param filePath }
*/ File file = new File(filePath);
public static boolean creatFiles(String filePath) { if (!file.exists()) {
LOGGER.info("【文件API】创建文件,同时创建整个路径.<START>.[filePath]=" + filePath); try {
if (StringUtil.isEmpty(filePath)) { file.createNewFile();
return false; return true;
} } catch (Exception e) {
filePath = filePath.replace(File.separator, "/"); LOGGER.error("【文件工具】创建文件失败,<ERROR>:" + e.getMessage(), e);
String dirPath = filePath.substring(0, filePath.lastIndexOf("/")); }
File dirFile = new File(dirPath); }
if (!dirFile.exists()) { return false;
try { }
dirFile.mkdirs();
} catch (Exception e) { /**
LOGGER.error("【文件工具】创建文件夹失败,<ERROR>:" + e.getMessage(), e); * 该方法用来判断文件是否存在,如果不存在则创建,该方法能够实现创建整个路径
return false; *
} * @param filePath
} */
File file = new File(filePath); public static boolean creatFiles(String filePath) {
if (!file.exists()) { LOGGER.info("【文件API】创建文件,同时创建整个路径.<START>.[filePath]=" + filePath);
try { if (StringUtil.isEmpty(filePath)) {
file.createNewFile(); return false;
return true; }
} catch (Exception e) { filePath = filePath.replace(File.separator, "/");
LOGGER.error("【文件工具】创建文件失败,<ERROR>:" + e.getMessage(), e); String dirPath = filePath.substring(0, filePath.lastIndexOf("/"));
} File dirFile = new File(dirPath);
} if (!dirFile.exists()) {
LOGGER.info("【文件API】创建文件,同时创建整个路径.<END>"); try {
return false; dirFile.mkdirs();
} } catch (Exception e) {
LOGGER.error("【文件工具】创建文件夹失败,<ERROR>:" + e.getMessage(), e);
/** return false;
* 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做 }
* }
* @param filePath File file = new File(filePath);
*/ if (!file.exists()) {
public static boolean creatDir(String filePath) { try {
if (StringUtil.isEmpty(filePath)) { file.createNewFile();
return false; return true;
} } catch (Exception e) {
File file = new File(filePath); LOGGER.error("【文件工具】创建文件失败,<ERROR>:" + e.getMessage(), e);
if (!file.exists()) { }
file.mkdir(); }
return true; LOGGER.info("【文件API】创建文件,同时创建整个路径.<END>");
} return false;
return false; }
}
/**
/** * 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做
* 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做 该方法能够实现创建整个路径 *
* * @param filePath
* @param filePath */
*/ public static boolean creatDir(String filePath) {
public static boolean creatDirs(String filePath) { if (StringUtil.isEmpty(filePath)) {
if (StringUtil.isEmpty(filePath)) { return false;
return false; }
} File file = new File(filePath);
File file = new File(filePath); if (!file.exists()) {
if (!file.exists()) { file.mkdir();
file.mkdirs(); return true;
return true; }
} return false;
return false; }
}
/**
/** * 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做 该方法能够实现创建整个路径
* 获取文件类型 *
* * @param filePath
* @param filePath */
*/ public static boolean creatDirs(String filePath) {
public static String getFileType(String filePath) { if (StringUtil.isEmpty(filePath)) {
if (StringUtil.isEmpty(filePath)) { return false;
return null; }
} File file = new File(filePath);
int index1 = filePath.lastIndexOf("."); if (!file.exists()) {
if (index1 < 1) { file.mkdirs();
return null; return true;
} }
int index2 = filePath.lastIndexOf("?"); return false;
if (index2 > index1) { }
filePath = filePath.substring(0, filePath.lastIndexOf("?"));
} /**
filePath = filePath.replace("/", OSConstant.SEPARATOR); * 获取文件类型
int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR); *
if (index3 > index1) { * @param filePath
return null; */
} public static String getFileType(String filePath) {
return filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()).toLowerCase(); if (StringUtil.isEmpty(filePath)) {
} return null;
}
/** int index1 = filePath.lastIndexOf(".");
* 获取文件名称 if (index1 < 1) {
* return null;
* @param filePath }
*/ int index2 = filePath.lastIndexOf("?");
public static String getFileName(String filePath) { if (index2 > index1) {
if (StringUtil.isEmpty(filePath)) { filePath = filePath.substring(0, filePath.lastIndexOf("?"));
return null; }
} filePath = filePath.replace("/", OSConstant.SEPARATOR);
String fileName = null; int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR);
filePath = filePath.replace("/", OSConstant.SEPARATOR); if (index3 > index1) {
int index1 = filePath.lastIndexOf("."); return null;
if (index1 > -1) { }
int index2 = filePath.lastIndexOf("?"); return filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()).toLowerCase();
if (index2 > index1) { }
filePath = filePath.substring(0, filePath.lastIndexOf("?"));
} /**
int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR); * 获取文件名称
if (index3 > index1) { *
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1); * @param filePath
} else { */
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1, public static String getFileName(String filePath) {
filePath.lastIndexOf(".")); if (StringUtil.isEmpty(filePath)) {
} return null;
} else { }
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1); String fileName = null;
} filePath = filePath.replace("/", OSConstant.SEPARATOR);
return formatName(fileName); int index1 = filePath.lastIndexOf(".");
} if (index1 > -1) {
int index2 = filePath.lastIndexOf("?");
/** if (index2 > index1) {
* 获取文件名称包括后缀 filePath = filePath.substring(0, filePath.lastIndexOf("?"));
* }
* @param filePath int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR);
* @return if (index3 > index1) {
*/ fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1);
public static String getFileNameAll(String filePath) { } else {
if (StringUtil.isEmpty(filePath)) { fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1,
return null; filePath.lastIndexOf("."));
} }
String fileName = getFileName(filePath); } else {
if (StringUtil.isEmpty(fileName)) { fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1);
return null; }
} return formatName(fileName);
String fileType = getFileType(filePath); }
return StringUtil.isEmpty(fileType) ? fileName : fileName + "." + fileType;
} /**
* 获取文件名称包括后缀
/** *
* 格式化文件名称,过滤特殊字符(名称太长进行截断) * @param filePath
* * @return
* @param fileName */
*/ public static String getFileNameAll(String filePath) {
public static String formatName(String fileName) { if (StringUtil.isEmpty(filePath)) {
if (StringUtil.isEmpty(fileName)) { return null;
return null; }
} String fileName = getFileName(filePath);
try { if (StringUtil.isEmpty(fileName)) {
String regEx = "[*/\\\\:?\"<|>\\s+%#&=.()]"; return null;
Pattern p = Pattern.compile(regEx); }
Matcher m = p.matcher(fileName); String fileType = getFileType(filePath);
String result = m.replaceAll("").trim(); return StringUtil.isEmpty(fileType) ? fileName : fileName + "." + fileType;
// 文件名称过长的话,限制40个字 }
return result.length() > 40 ? result.substring(0, 40) : result;
} catch (Exception e) { /**
LOGGER.error("【文件API】格式化文件名称.[formatName]:" + e.getMessage(), e); * 格式化文件名称,过滤特殊字符(名称太长进行截断)
return UUIDUitl.taskName(); *
} * @param fileName
} */
public static String formatName(String fileName) {
/** if (StringUtil.isEmpty(fileName)) {
* 获取文件所在的目录 return null;
* }
* @param filePath try {
* @return String regEx = "[*/\\\\:?\"<|>\\s+%#&=.()]";
*/ Pattern p = Pattern.compile(regEx);
public static String getFileFolder(String filePath) { Matcher m = p.matcher(fileName);
if (StringUtil.isEmpty(filePath)) { String result = m.replaceAll("").trim();
return null; // 文件名称过长的话,限制40个字
} return result.length() > 40 ? result.substring(0, 40) : result;
return filePath.substring(0, filePath.lastIndexOf(OSConstant.SEPARATOR)); } catch (Exception e) {
} LOGGER.error("【文件API】格式化文件名称.[formatName]:" + e.getMessage(), e);
return UUIDUitl.taskName();
/** }
* 获取http文件路径的域名 }
*
* @param fileUrl /**
* @return * 获取文件所在的目录
*/ *
public static String getDomainName(String fileUrl) { * @param filePath
if (StringUtil.isEmpty(fileUrl)) { * @return
return null; */
} public static String getFileFolder(String filePath) {
Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+"); if (StringUtil.isEmpty(filePath)) {
Matcher m = p.matcher(fileUrl); return null;
if (m.find()) { }
return m.group(); return filePath.substring(0, filePath.lastIndexOf(OSConstant.SEPARATOR));
} }
return null;
} /**
* 获取http文件路径的域名
/** *
* FileUtils工具 File @throws * @param fileUrl
*/ * @return
public static File copyURLToFile(String url, String dir) throws Exception { */
try { public static String getDomainName(String fileUrl) {
URL httpurl = new URL(url); if (StringUtil.isEmpty(fileUrl)) {
File f = new File(dir); return null;
org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f); }
return f; Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
} catch (Exception e) { Matcher m = p.matcher(fileUrl);
e.printStackTrace(); if (m.find()) {
} return m.group();
return null; }
} return null;
}
/**
* 根据路径删除指定的目录或文件,无论存在与否 /**
* * FileUtils工具 File @throws
* @param sPath 要删除的目录或文件 */
* @return 删除成功返回 true,否则返回 false。 public static File copyURLToFile(String url, String dir) throws Exception {
*/ try {
public static boolean deleteFolder(String sPath) { URL httpurl = new URL(url);
if (StringUtil.isEmpty(sPath)) { File f = new File(dir);
return false; org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f);
} return f;
boolean flag = false; } catch (Exception e) {
File file = new File(sPath); e.printStackTrace();
// 判断目录或文件是否存在 }
if (!file.exists()) { // 不存在返回 false return null;
return flag; }
} else {
// 判断是否为文件 /**
if (file.isFile()) { // 为文件时调用删除文件方法 * 根据路径删除指定的目录或文件,无论存在与否
return deleteFile(sPath); *
} else { // 为目录时调用删除目录方法 * @param sPath 要删除的目录或文件
return deleteDirectory(sPath); * @return 删除成功返回 true,否则返回 false。
} */
} public static boolean deleteFolder(String sPath) {
} if (StringUtil.isEmpty(sPath)) {
return false;
/** }
* 删除单个文件 boolean flag = false;
* File file = new File(sPath);
* @param sPath 被删除文件的文件名 // 判断目录或文件是否存在
* @return 单个文件删除成功返回true,否则返回false if (!file.exists()) { // 不存在返回 false
*/ return flag;
public static boolean deleteFile(String sPath) { } else {
if (StringUtil.isEmpty(sPath)) { // 判断是否为文件
return false; if (file.isFile()) { // 为文件时调用删除文件方法
} return deleteFile(sPath);
boolean flag = false; } else { // 为目录时调用删除目录方法
File file = new File(sPath); return deleteDirectory(sPath);
// 路径为文件且不为空则进行删除 }
if (file.isFile() && file.exists()) { }
file.delete(); }
flag = true;
} /**
return flag; * 删除单个文件
} *
* @param sPath 被删除文件的文件名
/** * @return 单个文件删除成功返回true,否则返回false
* 删除目录(文件夹)以及目录下的文件 */
* public static boolean deleteFile(String sPath) {
* @param sPath 被删除目录的文件路径 if (StringUtil.isEmpty(sPath)) {
* @return 目录删除成功返回true,否则返回false return false;
*/ }
public static boolean deleteDirectory(String sPath) { boolean flag = false;
if (StringUtil.isEmpty(sPath)) { File file = new File(sPath);
return false; // 路径为文件且不为空则进行删除
} if (file.isFile() && file.exists()) {
// 如果sPath不以文件分隔符结尾,自动添加文件分隔符 file.delete();
if (!sPath.endsWith(File.separator)) { flag = true;
sPath = sPath + File.separator; }
} return flag;
File dirFile = new File(sPath); }
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) { /**
return false; * 删除目录(文件夹)以及目录下的文件
} *
boolean flag = true; * @param sPath 被删除目录的文件路径
// 删除文件夹下的所有文件(包括子目录) * @return 目录删除成功返回true,否则返回false
File[] files = dirFile.listFiles(); */
for (int i = 0; i < files.length; i++) { public static boolean deleteDirectory(String sPath) {
// 删除子文件 if (StringUtil.isEmpty(sPath)) {
if (files[i].isFile()) { return false;
flag = deleteFile(files[i].getAbsolutePath()); }
if (!flag) // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
break; if (!sPath.endsWith(File.separator)) {
} // 删除子目录 sPath = sPath + File.separator;
else { }
flag = deleteDirectory(files[i].getAbsolutePath()); File dirFile = new File(sPath);
if (!flag) // 如果dir对应的文件不存在,或者不是一个目录,则退出
break; if (!dirFile.exists() || !dirFile.isDirectory()) {
} return false;
} }
if (!flag) boolean flag = true;
return false; // 删除文件夹下的所有文件(包括子目录)
// 删除当前目录 File[] files = dirFile.listFiles();
if (dirFile.delete()) { for (int i = 0; i < files.length; i++) {
return true; // 删除子文件
} else { if (files[i].isFile()) {
return false; flag = deleteFile(files[i].getAbsolutePath());
} if (!flag)
} break;
} // 删除子目录
/** else {
* 检查文件是否存在 flag = deleteDirectory(files[i].getAbsolutePath());
* if (!flag)
* @param filePath break;
* @return }
*/ }
public static boolean checkFile(String filePath) { if (!flag)
if (StringUtil.isEmpty(filePath)) { return false;
return false; // 删除当前目录
} if (dirFile.delete()) {
File file = new File(filePath); return true;
if (!file.isFile()) { } else {
return false; return false;
} }
return true; }
}
/**
/** * 检查文件是否存在
* | FileUtils工具 *
*/ * @param filePath
public static void downloadFileFromUrl(String url, String localFilePath) throws FileException { * @return
LOGGER.info("【文件API】下载文件[本地文件].<START>.[url]=" + url + ",[localFilePath]=" + localFilePath); */
creatFiles(localFilePath); public static boolean checkFile(String filePath) {
try { if (StringUtil.isEmpty(filePath)) {
if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) { return false;
OssUtils.downloadFile(url, localFilePath); }
// } else if (url.contains("/group")) { File file = new File(filePath);
// Map<String, String> paramMap = FdfsUtils.splitFilePath(url); if (!file.isFile()) {
// FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value), return false;
// paramMap.get(FdfsEnum.FILE_ID.value), localFilePath); }
} else { return true;
File f = new File(localFilePath); }
URL httpurl = new URL(url);
org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f); /**
} * | FileUtils工具
} catch (Exception e) { */
LOGGER.error("【文件API】下载文件.[copyURLToFile]:" + e.getMessage(), e); public static void downloadFileFromUrl(String url, String localFilePath) throws FileException {
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败"); LOGGER.info("【文件API】下载文件[本地文件].<START>.[url]=" + url + ",[localFilePath]=" + localFilePath);
} creatFiles(localFilePath);
} try {
if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) {
/** OssUtils.downloadFile(url, localFilePath);
* IOUtils工具 // } else if (url.contains("/group")) {
*/ // Map<String, String> paramMap = FdfsUtils.splitFilePath(url);
public static byte[] downloadByteFromUrl(String url) throws FileException { // FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value),
LOGGER.info("【文件API】下载文件[byte].<START>.[url]=" + url); // paramMap.get(FdfsEnum.FILE_ID.value), localFilePath);
if (StringUtil.isEmpty(url)) { } else {
return null; File f = new File(localFilePath);
} URL httpurl = new URL(url);
byte[] data = null; org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f);
try { }
if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) { } catch (Exception e) {
data = OssUtils.downloadFile2Byte(url); LOGGER.error("【文件API】下载文件.[copyURLToFile]:" + e.getMessage(), e);
// } else if (url.contains("/group")) { throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
// Map<String, String> paramMap = FdfsUtils.splitFilePath(url); }
// data = }
// FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value),
// paramMap.get(FdfsEnum.FILE_ID.value)); /**
} else { * IOUtils工具
URL httpurl = new URL(url); */
data = IOUtils.toByteArray(httpurl); public static byte[] downloadByteFromUrl(String url) throws FileException {
} LOGGER.info("【文件API】下载文件[byte].<START>.[url]=" + url);
} catch (Exception e) { if (StringUtil.isEmpty(url)) {
LOGGER.error("【文件API】下载文件.[toByteArray]:" + e.getMessage(), e); return null;
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败"); }
} byte[] data = null;
return data; try {
} if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) {
data = OssUtils.downloadFile2Byte(url);
/** // } else if (url.contains("/group")) {
* InputStream // Map<String, String> paramMap = FdfsUtils.splitFilePath(url);
*/ // data =
@Deprecated // FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value),
public static InputStream downloadStreamFromUrl(String url) throws FileException { // paramMap.get(FdfsEnum.FILE_ID.value));
try { } else {
URL httpurl = new URL(url); URL httpurl = new URL(url);
return httpurl.openStream(); data = IOUtils.toByteArray(httpurl);
} catch (Exception e) { }
LOGGER.error("【文件API】下载文件.[openStream]:" + e.getMessage(), e); } catch (Exception e) {
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败"); LOGGER.error("【文件API】下载文件.[toByteArray]:" + e.getMessage(), e);
} throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
} }
return data;
/** }
* 普通情况下保存字节数据到本地文件
*/ /**
public synchronized static boolean saveBytesTofile(File file, byte[] data) throws BizException { * InputStream
FileOutputStream fos = null; */
// 建立输出字节流 @Deprecated
try { public static InputStream downloadStreamFromUrl(String url) throws FileException {
fos = new FileOutputStream(file); try {
fos.write(data); // 用FileOutputStream 的write方法写入字节数组 URL httpurl = new URL(url);
return true; return httpurl.openStream();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); LOGGER.error("【文件API】下载文件.[openStream]:" + e.getMessage(), e);
return false; throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
} finally { }
try { }
fos.close();
} catch (IOException e) { /**
e.printStackTrace(); * 普通情况下保存字节数据到本地文件
} */
} public synchronized static boolean saveBytesTofile(File file, byte[] data) throws BizException {
} FileOutputStream fos = null;
// 建立输出字节流
/** try {
* 复制一个文件到另一个目录下 fos = new FileOutputStream(file);
* fos.write(data); // 用FileOutputStream 的write方法写入字节数组
* @throws BizException return true;
*/ } catch (Exception e) {
public static void copyFileToFolder(File inputFile, File outputFile) throws BizException { e.printStackTrace();
FileInputStream fis = null; return false;
FileOutputStream fos = null; } finally {
try {
try { fos.close();
fis = new FileInputStream(inputFile); } catch (IOException e) {
fos = new FileOutputStream(outputFile); e.printStackTrace();
int len = 0; }
byte[] buf = new byte[1024]; }
while ((len = fis.read(buf)) != -1) { }
fos.write(buf, 0, len);
} /**
fis.close(); * 复制一个文件到另一个目录下
fos.close(); *
} catch (IOException ioe) { * @throws BizException
ioe.printStackTrace(); */
} public static void copyFileToFolder(File inputFile, File outputFile) throws BizException {
} FileInputStream fis = null;
FileOutputStream fos = null;
/**
* 合并两个文件 try {
* fis = new FileInputStream(inputFile);
* @param outFile 目标文件 fos = new FileOutputStream(outputFile);
* @param leafFile 源文件 int len = 0;
*/ byte[] buf = new byte[1024];
public static void mergeFiles(File outFile, File leafFile) { while ((len = fis.read(buf)) != -1) {
FileOutputStream fos = null; fos.write(buf, 0, len);
FileInputStream fis = null; }
if (!outFile.exists()) { fis.close();
try { fos.close();
outFile.createNewFile(); } catch (IOException ioe) {
} catch (Exception e) { ioe.printStackTrace();
throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败"); }
} }
}
try { /**
// 合并其实就是文件的续写,写成true * 合并两个文件
fos = new FileOutputStream(outFile, true); *
fis = new FileInputStream(leafFile); * @param outFile 目标文件
int len = 0; * @param leafFile 源文件
for (byte[] buf = new byte[1024 * 1024]; (len = fis.read(buf)) != -1; ) { */
fos.write(buf, 0, len); public static void mergeFiles(File outFile, File leafFile) {
} FileOutputStream fos = null;
} catch (IOException ioe) { FileInputStream fis = null;
ioe.printStackTrace(); if (!outFile.exists()) {
} finally { try {
try { outFile.createNewFile();
if (fis != null) } catch (Exception e) {
fis.close(); throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败");
if (fos != null) }
fos.close(); }
} catch (Exception e) { try {
} // 合并其实就是文件的续写,写成true
} fos = new FileOutputStream(outFile, true);
} fis = new FileInputStream(leafFile);
int len = 0;
/** for (byte[] buf = new byte[1024 * 1024]; (len = fis.read(buf)) != -1; ) {
* 合并多个文件 fos.write(buf, 0, len);
* }
* @param outFile 输出文件, } catch (IOException ioe) {
* @param leafFiles 文件碎片集 ioe.printStackTrace();
*/ } finally {
public static void mergeFileList(File outFile, List<File> leafFiles) { try {
FileOutputStream fos = null; if (fis != null)
FileInputStream fis = null; fis.close();
if (!outFile.exists()) { if (fos != null)
try { fos.close();
outFile.createNewFile(); } catch (Exception e) {
} catch (Exception e) { }
throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败"); }
} }
}
try { /**
// 合并其实就是文件的续写,写成true * 合并多个文件
fos = new FileOutputStream(outFile, true); *
byte[] buf = new byte[1024 * 1024]; * @param outFile 输出文件,
for (File leafFile : leafFiles) { * @param leafFiles 文件碎片集
fis = new FileInputStream(leafFile); */
int len = 0; public static void mergeFileList(File outFile, List<File> leafFiles) {
while ((len = fis.read(buf)) != -1) { FileOutputStream fos = null;
fos.write(buf, 0, len); FileInputStream fis = null;
} if (!outFile.exists()) {
} try {
} catch (IOException ioe) { outFile.createNewFile();
ioe.printStackTrace(); } catch (Exception e) {
} finally { throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败");
try { }
if (fis != null) }
fis.close(); try {
if (fos != null) // 合并其实就是文件的续写,写成true
fos.close(); fos = new FileOutputStream(outFile, true);
} catch (Exception e) { byte[] buf = new byte[1024 * 1024];
} for (File leafFile : leafFiles) {
} fis = new FileInputStream(leafFile);
} int len = 0;
while ((len = fis.read(buf)) != -1) {
/** fos.write(buf, 0, len);
* 音频文件转换 }
* }
* @param data 音频byte数组 } catch (IOException ioe) {
* @param sourExt 原始后缀 ioe.printStackTrace();
* @param ext 新后缀 } finally {
* @return try {
* @author PENG if (fis != null)
*/ fis.close();
public static String audioFormatConvert(byte[] data, String sourExt, String ext) { if (fos != null)
File tmpdir = new File("tempdir/local"); fos.close();
if (!tmpdir.exists()) { } catch (Exception e) {
try { }
tmpdir.mkdirs(); }
} catch (SecurityException ex) { }
System.out.println("无法创建临时文件夹");
ex.printStackTrace(); /**
} * 音频文件转换
} *
* @param data 音频byte数组
String name = UUID.randomUUID().toString(); * @param sourExt 原始后缀
File source = new File(tmpdir, name + "." + sourExt); * @param ext 新后缀
boolean creat = saveBytesTofile(source, data); * @return
if (creat) { * @author PENG
File target = new File(tmpdir, name + "." + ext); */
AudioAttributes audio = new AudioAttributes(); public static String audioFormatConvert(byte[] data, String sourExt, String ext) {
Encoder encoder = new Encoder(); File tmpdir = new File("tempdir/local");
audio.setCodec("libmp3lame"); if (!tmpdir.exists()) {
try {
EncodingAttributes attrs = new EncodingAttributes(); tmpdir.mkdirs();
attrs.setFormat(ext.toLowerCase()); } catch (SecurityException ex) {
attrs.setAudioAttributes(audio); System.out.println("无法创建临时文件夹");
ex.printStackTrace();
try { }
encoder.encode(source, target, attrs); }
return target.getPath();
} catch (IllegalArgumentException e) { String name = UUID.randomUUID().toString();
e.printStackTrace(); File source = new File(tmpdir, name + "." + sourExt);
return null; boolean creat = saveBytesTofile(source, data);
} catch (InputFormatException e) { if (creat) {
e.printStackTrace(); File target = new File(tmpdir, name + "." + ext);
return null; AudioAttributes audio = new AudioAttributes();
} catch (EncoderException e) { Encoder encoder = new Encoder();
e.printStackTrace(); audio.setCodec("libmp3lame");
return target.getPath();
} EncodingAttributes attrs = new EncodingAttributes();
} else { attrs.setFormat(ext.toLowerCase());
return null; attrs.setAudioAttributes(audio);
}
} try {
encoder.encode(source, target, attrs);
/** return target.getPath();
* 获取文本的内容 } catch (IllegalArgumentException e) {
* e.printStackTrace();
* @param url return null;
* @return } catch (InputFormatException e) {
*/ e.printStackTrace();
public static String getTextString(String url) { return null;
LOGGER.info("【文件API】获取文本的内容.<START>.[url]=" + url); } catch (EncoderException e) {
if (StringUtil.isEmpty(url)) { e.printStackTrace();
return null; return target.getPath();
} }
StringBuilder lrcString = new StringBuilder(); } else {
InputStream is = null; return null;
InputStreamReader isr = null; }
try { }
byte[] bt = downloadByteFromUrl(url);
is = new ByteArrayInputStream(bt); /**
boolean isUTF8Bom = CpdetectorEncoding.isUTF8Bom(is); * 获取文本的内容
if (isUTF8Bom) { *
isr = new InputStreamReader(is, "UTF-8"); * @param url
} else { * @return
Object charSet = CpdetectorEncoding.getEncoding(bt, false); */
if (charSet.toString().equals("UTF-8")) { public static String getTextString(String url) {
isr = new InputStreamReader(is, "UTF-8"); LOGGER.info("【文件API】获取文本的内容.<START>.[url]=" + url);
} else { if (StringUtil.isEmpty(url)) {
isr = new InputStreamReader(new ByteArrayInputStream(bt), "GBK"); return null;
} }
} StringBuilder lrcString = new StringBuilder();
BufferedReader br = new BufferedReader(isr);// 构造一个BufferedReader类来读取文件 InputStream is = null;
String s; InputStreamReader isr = null;
while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行 try {
lrcString.append(System.lineSeparator() + s); byte[] bt = downloadByteFromUrl(url);
} is = new ByteArrayInputStream(bt);
} catch (Exception e) { boolean isUTF8Bom = CpdetectorEncoding.isUTF8Bom(is);
LOGGER.error("【文件工具】读取文件内容.<ERROR>:" + e.getMessage(), e); if (isUTF8Bom) {
} finally { isr = new InputStreamReader(is, "UTF-8");
try { } else {
if (isr != null) Object charSet = CpdetectorEncoding.getEncoding(bt, false);
isr.close(); if (charSet.toString().equals("UTF-8")) {
if (is != null) isr = new InputStreamReader(is, "UTF-8");
is.close(); } else {
} catch (Exception e2) { isr = new InputStreamReader(new ByteArrayInputStream(bt), "GBK");
} }
} }
LOGGER.info("【文件API】获取文本的内容.<END>"); BufferedReader br = new BufferedReader(isr);// 构造一个BufferedReader类来读取文件
return lrcString.toString(); String s;
} while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行
lrcString.append(System.lineSeparator() + s);
/** }
* java 8 读取文本内容 } catch (Exception e) {
* LOGGER.error("【文件工具】读取文件内容.<ERROR>:" + e.getMessage(), e);
* @param url } finally {
* @return try {
*/ if (isr != null)
public static String getTextString8(String url) { isr.close();
LOGGER.info("【文件API】获取文本的内容8.<START>.[url]=" + url); if (is != null)
StringBuilder result = new StringBuilder(); is.close();
String fileType = getFileType(url); } catch (Exception e2) {
String localFilePath = url; }
if (url.startsWith("http")) { }
localFilePath = FilePathConst.TEXT_PATH + UUIDUitl.taskName() + "." + fileType; LOGGER.info("【文件API】获取文本的内容.<END>");
downloadFileFromUrl(url, localFilePath); return lrcString.toString();
} }
try {
Stream<String> lines = Files.lines(Paths.get(localFilePath), StandardCharsets.UTF_8); /**
lines.forEach(line -> { * java 8 读取文本内容
result.append(line + System.lineSeparator()); *
}); * @param url
} catch (Exception e) { * @return
LOGGER.error("【文件工具】读取文件内容8.<ERROR>:" + e.getMessage(), e); */
} finally { public static String getTextString8(String url) {
deleteFile(localFilePath); LOGGER.info("【文件API】获取文本的内容8.<START>.[url]=" + url);
} StringBuilder result = new StringBuilder();
LOGGER.info("【文件API】获取文本的内容8.<END>"); String fileType = getFileType(url);
return result.toString(); String localFilePath = url;
} if (url.startsWith("http")) {
localFilePath = FilePathConst.TEXT_PATH + UUIDUitl.taskName() + "." + fileType;
/** downloadFileFromUrl(url, localFilePath);
* 文件剪切,网络路径、按文件大小的百分比 }
* try {
* @param url Stream<String> lines = Files.lines(Paths.get(localFilePath), StandardCharsets.UTF_8);
* @param percent 1~100的整数 lines.forEach(line -> {
* @return 返回剪切后上传后的文件路径 result.append(line + System.lineSeparator());
* @throws BizException });
*/ lines.close();
public static String clipByPercent(String url, int percent) throws BizException { } catch (Exception e) {
LOGGER.info("【文件API】文件剪切,按百分比.<START>.[url]=" + url); LOGGER.error("【文件工具】读取文件内容8.<ERROR>:" + e.getMessage(), e);
if (StringUtil.isEmpty(url)) { } finally {
return null; deleteFile(localFilePath);
} }
String fileType = FileUtils.getFileType(url); LOGGER.info("【文件API】获取文本的内容8.<END>");
if (!FileUtils.VIDEO.equals(FileUtils.getGatherName(fileType))) { return result.toString();
return null; }
}
// 下载文件 /**
String downloadPath = FilePathConst.DOWNLOAD_PATH + UUIDUitl.generateString(32) + "." + fileType; * 文件剪切,网络路径、按文件大小的百分比
FileUtils.downloadFileFromUrl(url, downloadPath); *
// 剪切文件 * @param url
String cutPath = clipByPercent(new File(downloadPath), percent); * @param percent
// 重新上传文件 * 1~100的整数
UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile(cutPath, null); * @return 返回剪切后上传后的文件路径
// 删除本地文件 * @throws BizException
FileUtils.deleteFile(downloadPath); */
FileUtils.deleteFile(cutPath); public static String clipByPercent(String url, int percent) throws BizException {
LOGGER.info("【文件API】文件剪切,按百分比.<END>.[uploadResultInfo]=" + uploadResultInfo); LOGGER.info("【文件API】文件剪切,按百分比.<START>.[url]=" + url);
return uploadResultInfo == null ? null : uploadResultInfo.getUrl(); if (StringUtil.isEmpty(url)) {
} return null;
}
/** String fileType = FileUtils.getFileType(url);
* 文件剪切,本地路径、按百分比 if (!FileUtils.VIDEO.equals(FileUtils.getGatherName(fileType))) {
* return null;
* @param inputFile }
* @param cutPercent 1~100的整数 // 下载文件
* @return 返回本地路径地址 String downloadPath = FilePathConst.DOWNLOAD_PATH + UUIDUitl.generateString(32) + "." + fileType;
* @throws BizException FileUtils.downloadFileFromUrl(url, downloadPath);
*/ // 剪切文件
public static String clipByPercent(File inputFile, int cutPercent) throws BizException { String cutPath = clipByPercent(new File(downloadPath), percent);
LOGGER.info("【文件API】文件剪切.<START>.[cutPercent]=" + cutPercent); // 重新上传文件
if (inputFile == null || inputFile.length() <= 0) { UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile(cutPath, null);
throw new FileException(FileException.FILE_NOT_EXIST, "不是有效的文件"); // 删除本地文件
} FileUtils.deleteFile(downloadPath);
if (cutPercent > 100 || cutPercent < 1) { FileUtils.deleteFile(cutPath);
throw new FileException(FileException.FILE_READ_FAILURE, "百分比必须是1~100之间的整数"); LOGGER.info("【文件API】文件剪切,按百分比.<END>.[uploadResultInfo]=" + uploadResultInfo);
} return uploadResultInfo == null ? null : uploadResultInfo.getUrl();
return clipByLength(inputFile, Math.round(inputFile.length() * cutPercent / 100.0d)); }
}
/**
/** * 文件剪切,本地路径、按百分比
* 文件剪切 *
* * @param inputFile
* @param inputFile 待剪切的文件 * @param cutPercent
* @param cutLength 剪切长度(Byte) * 1~100的整数
*/ * @return 返回本地路径地址
public static String clipByLength(File inputFile, long cutLength) throws BizException { * @throws BizException
LOGGER.info("【文件API】文件剪切.<START>.[cutLength]=" + cutLength); */
if (inputFile == null || inputFile.length() <= 0) { public static String clipByPercent(File inputFile, int cutPercent) throws BizException {
throw new FileException(FileException.FILE_NOT_EXIST, "不是有效的文件"); LOGGER.info("【文件API】文件剪切.<START>.[cutPercent]=" + cutPercent);
} if (inputFile == null || inputFile.length() <= 0) {
if (cutLength < 1024) { throw new FileException(FileException.FILE_NOT_EXIST, "不是有效的文件");
throw new FileException(FileException.FILE_READ_FAILURE, "剪切的文件必须大于1KB"); }
} if (cutPercent > 100 || cutPercent < 1) {
// 输出文件路径 throw new FileException(FileException.FILE_READ_FAILURE, "百分比必须是1~100之间的整数");
String outFilePath = FilePathConst.CUT_PATH + UUIDUitl.generateString(12) + "_" + inputFile.getName(); }
creatFiles(outFilePath); return clipByLength(inputFile, Math.round(inputFile.length() * cutPercent / 100.0d));
// 剪切长度 }
cutLength = cutLength > inputFile.length() ? inputFile.length() : cutLength;
BufferedInputStream bis = null; /**
BufferedOutputStream bos = null; * 文件剪切
try { *
// 两个输入流 * @param inputFile
bis = new BufferedInputStream(new FileInputStream(inputFile)); * 待剪切的文件
// 缓冲字节输出流 * @param cutLength
bos = new BufferedOutputStream(new FileOutputStream(outFilePath)); * 剪切长度(Byte)
// 读取多少次 */
long index = cutLength % 1024 > 0 ? cutLength / 1024 + 1 : cutLength / 1024; public static String clipByLength(File inputFile, long cutLength) throws BizException {
int mod = (int) cutLength % 1024; LOGGER.info("【文件API】文件剪切.<START>.[cutLength]=" + cutLength);
byte[] bt = new byte[1024]; if (inputFile == null || inputFile.length() <= 0) {
int len = 0; throw new FileException(FileException.FILE_NOT_EXIST, "不是有效的文件");
for (int i = 0; i < index; i++) { }
if (i + 1 == index && mod != 0) { if (cutLength < 1024) {
bt = new byte[mod]; throw new FileException(FileException.FILE_READ_FAILURE, "剪切的文件必须大于1KB");
len = bis.read(bt); }
} else { // 输出文件路径
len = bis.read(bt); String outFilePath = FilePathConst.CUT_PATH + UUIDUitl.generateString(12) + "_" + inputFile.getName();
} creatFiles(outFilePath);
if (len != -1) { // 剪切长度
bos.write(bt, 0, len); cutLength = cutLength > inputFile.length() ? inputFile.length() : cutLength;
} BufferedInputStream bis = null;
} BufferedOutputStream bos = null;
bos.flush(); try {
} catch (IOException e) { // 两个输入流
LOGGER.error("【文件工具】剪切文件内容:" + e.getMessage(), e); bis = new BufferedInputStream(new FileInputStream(inputFile));
throw new FileException(FileException.FILE_READ_FAILURE, "文件剪切失败"); // 缓冲字节输出流
} finally { bos = new BufferedOutputStream(new FileOutputStream(outFilePath));
try { // 读取多少次
if (bis != null) long index = cutLength % 1024 > 0 ? cutLength / 1024 + 1 : cutLength / 1024;
bis.close(); int mod = (int) cutLength % 1024;
if (bos != null) byte[] bt = new byte[1024];
bos.close(); int len = 0;
} catch (IOException e) { for (int i = 0; i < index; i++) {
LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e); if (i + 1 == index && mod != 0) {
} bt = new byte[mod];
} len = bis.read(bt);
LOGGER.info("【文件API】文件剪切.<END>"); } else {
return outFilePath; len = bis.read(bt);
} }
if (len != -1) {
/** bos.write(bt, 0, len);
* 将文件转成base64 字符串 }
* }
* @param data bos.flush();
* @return * } catch (IOException e) {
* @throws Exception LOGGER.error("【文件工具】剪切文件内容:" + e.getMessage(), e);
*/ throw new FileException(FileException.FILE_READ_FAILURE, "文件剪切失败");
public static String encodeBase64File(byte[] data) throws BizException { } finally {
try { try {
return new String(Base64.encodeBase64(data)); if (bis != null)
} catch (Exception e) { bis.close();
LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e); if (bos != null)
return null; bos.close();
} } catch (IOException e) {
} LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e);
}
/** }
* 将base64字符解码保存文件 LOGGER.info("【文件API】文件剪切.<END>");
* return outFilePath;
* @param base64Code }
* @param targetPath
* @throws Exception /**
*/ * 将文件转成base64 字符串
public static boolean decoderBase64File(String base64Code, String targetPath) throws BizException { *
if (base64Code == null) * @param data
return false; * @return *
OutputStream out = null; * @throws Exception
try { */
// Base64解码 public static String encodeBase64File(byte[] data) throws BizException {
byte[] b = Base64.decodeBase64(targetPath); try {
for (int i = 0; i < b.length; ++i) { return new String(Base64.encodeBase64(data));
if (b[i] < 0) {// 调整异常数据 } catch (Exception e) {
b[i] += 256; LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e);
} return null;
} }
// 生成jpeg图片 }
out = new FileOutputStream(targetPath);
out.write(b); /**
out.flush(); * 将base64字符解码保存文件
} catch (Exception e) { *
LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e); * @param base64Code
return false; * @param targetPath
} finally { * @throws Exception
try { */
if (out != null) public static boolean decoderBase64File(String base64Code, String targetPath) throws BizException {
out.close(); if (base64Code == null)
} catch (Exception e) { return false;
} OutputStream out = null;
} try {
return true; // Base64解码
} byte[] b = Base64.decodeBase64(targetPath);
for (int i = 0; i < b.length; ++i) {
/** if (b[i] < 0) {// 调整异常数据
* 本地文件到byte数组 b[i] += 256;
* }
* @param path }
* @return // 生成jpeg图片
*/ out = new FileOutputStream(targetPath);
public static byte[] file2byte(String path) { out.write(b);
byte[] data = null; out.flush();
FileInputStream fis = null; } catch (Exception e) {
ByteArrayOutputStream os = null; LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e);
try { return false;
fis = new FileInputStream(new File(path)); } finally {
os = new ByteArrayOutputStream(); try {
byte[] buf = new byte[1024]; if (out != null)
int numBytesRead = 0; out.close();
while ((numBytesRead = fis.read(buf)) != -1) { } catch (Exception e) {
os.write(buf, 0, numBytesRead); }
} }
data = os.toByteArray(); return true;
} catch (Exception e) { }
LOGGER.error("【文件工具】文件到byte数组:" + e.getMessage(), e);
} finally { /**
try { * 本地文件到byte数组
if (fis != null) *
fis.close(); * @param path
if (os != null) * @return
os.close(); */
} catch (IOException e) { public static byte[] file2byte(String path) {
LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e); byte[] data = null;
} FileInputStream fis = null;
} ByteArrayOutputStream os = null;
return data; try {
} fis = new FileInputStream(new File(path));
os = new ByteArrayOutputStream();
/** byte[] buf = new byte[1024];
* 从输入流中获取数据 int numBytesRead = 0;
* while ((numBytesRead = fis.read(buf)) != -1) {
* @param inStream 输入流 os.write(buf, 0, numBytesRead);
* @return }
* @throws Exception data = os.toByteArray();
*/ } catch (Exception e) {
public static byte[] readInputStream(InputStream inStream) throws Exception { LOGGER.error("【文件工具】文件到byte数组:" + e.getMessage(), e);
ByteArrayOutputStream outStream = new ByteArrayOutputStream(); } finally {
byte[] buffer = new byte[1024]; try {
int len = 0; if (fis != null)
try { fis.close();
while ((len = inStream.read(buffer)) != -1) { if (os != null)
outStream.write(buffer, 0, len); os.close();
} } catch (IOException e) {
} catch (Exception e) { LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e);
LOGGER.error("【文件工具】文件流到byte数组:" + e.getMessage(), e); }
} finally { }
inStream.close(); return data;
} }
return outStream.toByteArray();
} /**
* 从输入流中获取数据
} *
* @param inStream 输入流
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
try {
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
} catch (Exception e) {
LOGGER.error("【文件工具】文件流到byte数组:" + e.getMessage(), e);
} finally {
inStream.close();
}
return outStream.toByteArray();
}
}
...@@ -14,9 +14,12 @@ import javax.imageio.ImageIO; ...@@ -14,9 +14,12 @@ import javax.imageio.ImageIO;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.dcg.util.StringUtils;
import com.itextpdf.text.Image; import com.itextpdf.text.Image;
import com.pcloud.common.constant.AliyunConstant; import com.pcloud.common.constant.AliyunConstant;
import com.pcloud.common.constant.FilePathConst;
import com.pcloud.common.constant.ImageConstant; import com.pcloud.common.constant.ImageConstant;
import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.enums.ImageEnum; import com.pcloud.common.enums.ImageEnum;
import com.pcloud.common.exceptions.BizException; import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException; import com.pcloud.common.exceptions.FileException;
...@@ -688,4 +691,37 @@ public class ImageUtils { ...@@ -688,4 +691,37 @@ public class ImageUtils {
return size; return size;
} }
/**
* 上传的图片转换成webpO
*
* @param localFilePath
* 源文件的本地路径
* @param httpUrl
* 源文件上传后的路径,主要用于子文件上传时对应http文件路径
*/
public static UploadResultInfo toWebp(String fileUrl) {
String fileNameAll = FileUtils.getFileNameAll(fileUrl);
String localFilePath = FilePathConst.DOWNLOAD_PATH + fileNameAll;
FileUtils.downloadFileFromUrl(fileUrl, localFilePath);
String tragetPath = null;
try {
tragetPath = com.dcg.util.ImageUtils.transcodeToWebp(localFilePath, 80);
} catch (Exception e) {
LOGGER.error("【IMAGE】图片转换成webp失败:" + e.getMessage(), e);
return null;
}
if (StringUtils.isEmpty(tragetPath)) {
return null;
}
try {
return OssUtils.uploadLocalFile4Child(tragetPath, fileUrl);
} catch (Exception e) {
LOGGER.error("【IMAGE】图片转换成webp,上传失败:" + e.getMessage(), e);
} finally {
FileUtils.deleteFile(localFilePath);
FileUtils.deleteFile(tragetPath);
}
return null;
}
} }
...@@ -213,7 +213,7 @@ public class PictureUtil { ...@@ -213,7 +213,7 @@ public class PictureUtil {
header.put("Content-Type", "application/json"); header.put("Content-Type", "application/json");
Map<String,String>param = new HashMap<>(); Map<String,String>param = new HashMap<>();
param.put("htmlCode",html); param.put("htmlCode",html);
String postResult = HttpKit.post("http://192.168.92.111:8214/transcode/htm2img/jpg", JSON.toJSONString(param)); String postResult = HttpKit.post("http://192.168.1.7:8216/transcode/htm2img/jpg", JSON.toJSONString(param));
Map map = JSONUtils.jsonToMap(postResult, String.class, String.class); Map map = JSONUtils.jsonToMap(postResult, String.class, String.class);
String pic = (String)map.get("data"); String pic = (String)map.get("data");
BufferedImage bookPicImage = ImageIO.read(new URL(pic)); BufferedImage bookPicImage = ImageIO.read(new URL(pic));
......
...@@ -21,6 +21,7 @@ import java.util.Map; ...@@ -21,6 +21,7 @@ import java.util.Map;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.swing.ImageIcon; import javax.swing.ImageIcon;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -215,6 +216,42 @@ public class QrcodeUtils { ...@@ -215,6 +216,42 @@ public class QrcodeUtils {
} }
/** /**
* 创建二维码
*
* @param url
* 二维码响应地址
* @return
* @throws Exception
*/
public static String createWithMargin(String url, Integer marginNum) throws BizException {
String key = "createWithMargin:"+url+"_"+marginNum;
if(JedisClusterUtils.exists(key)){
String s = JedisClusterUtils.get(key);
return s;
}else {
LOGGER.info("【二维码】创建二维码,<START>.[url]=" + url);
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, level);
hints.put(EncodeHintType.MARGIN, marginNum); // 设置白边
try {
// 生成矩阵
BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, ImageConstant.QRCODE_WITH,
ImageConstant.QRCODE_HEIGHT, hints);
BufferedImage bufferedImage = toBufferedImage(bitMatrix, onColor);
bufferedImage.flush();
String s = uploadImage(bufferedImage);
JedisClusterUtils.set(key,s,24*3600);
return s;
} catch (Exception e) {
LOGGER.error("【二维码】创建二维码失败,<ERROR>:" + e.getMessage(), e);
throw new FileException(FileException.FILE_UPLOAD_FAILURE, "创建二维码失败");
}
}
}
/**
* 创建带颜色的二维码 * 创建带颜色的二维码
* @param url * @param url
* @param onColor * @param onColor
......
...@@ -17,43 +17,63 @@ import com.pcloud.common.page.PageBeanNew; ...@@ -17,43 +17,63 @@ import com.pcloud.common.page.PageBeanNew;
*/ */
public class ResultUtils { public class ResultUtils {
/** /**
* 集合查询结果判断 * 单个对象实例化
* *
* @param lists * @param t
* @return * @param clazz
*/ * @return
public static <T> List<T> list(List<T> lists) { * @author songx
if (!ListUtils.isEmpty(lists)) { * @date 2019年1月14日,下午7:32:35
return lists; */
} public static <T> T object(T t, Class<T> clazz) {
return Lists.newArrayList(); if (t == null) {
} return null;
}
/** try {
* map查询结果判断 return clazz.newInstance();
* } catch (Exception e) {
* @param lists }
* @return return null;
*/ }
public static <K, V> Map<K, V> map(Map<K, V> map) {
if (!MapUtils.isEmpty(map)) { /**
return map; * 集合查询结果判断
} *
return Maps.newHashMap(); * @param lists
} * @return
*/
/** public static <T> List<T> list(List<T> lists) {
* 分页查询结果判断 if (!ListUtils.isEmpty(lists)) {
* return lists;
* @param pageBeanNew }
* @return return Lists.newArrayList();
*/ }
public static <T> PageBeanNew<T> pageBeanNew(PageBeanNew<T> pageBeanNew, Integer currentPage, Integer numPerPage) {
if (pageBeanNew != null) { /**
return pageBeanNew; * map查询结果判断
} *
return new PageBeanNew<T>(currentPage, numPerPage, 0, Lists.newArrayList()); * @param lists
} * @return
*/
public static <K, V> Map<K, V> map(Map<K, V> map) {
if (!MapUtils.isEmpty(map)) {
return map;
}
return Maps.newHashMap();
}
/**
* 分页查询结果判断
*
* @param pageBeanNew
* @return
*/
public static <T> PageBeanNew<T> pageBeanNew(PageBeanNew<T> pageBeanNew, Integer currentPage, Integer numPerPage) {
if (pageBeanNew != null) {
return pageBeanNew;
}
return new PageBeanNew<T>(currentPage, numPerPage, 0, Lists.newArrayList());
}
} }
This source diff could not be displayed because it is too large. You can view the blob instead.
...@@ -12,6 +12,7 @@ import org.slf4j.Logger; ...@@ -12,6 +12,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.pcloud.common.exceptions.BizException; import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.NumberUtil;
import com.pcloud.common.utils.string.StringUtil; import com.pcloud.common.utils.string.StringUtil;
/** /**
...@@ -125,25 +126,25 @@ public class Cookie { ...@@ -125,25 +126,25 @@ public class Cookie {
String[] channel = userInfoArry[i].split("="); String[] channel = userInfoArry[i].split("=");
String channelId = channel[channel.length - 1]; String channelId = channel[channel.length - 1];
userInfos.put("channelId", StringUtil.isEmpty(channelId) || "undefined".equalsIgnoreCase(channelId) userInfos.put("channelId", StringUtil.isEmpty(channelId) || "undefined".equalsIgnoreCase(channelId)
|| "null".equalsIgnoreCase(channelId) ? null : Long.valueOf(channelId)); || "null".equalsIgnoreCase(channelId) ? null : NumberUtil.toLong(channelId));
} }
if (userInfoArry[i].contains("officialAccountsId")) { if (userInfoArry[i].contains("officialAccountsId")) {
String[] wechat = userInfoArry[i].split("="); String[] wechat = userInfoArry[i].split("=");
String officialAccountsId = wechat[wechat.length - 1]; String officialAccountsId = wechat[wechat.length - 1];
userInfos.put("officialAccountsId", StringUtil.isEmpty(officialAccountsId) || "undefined".equalsIgnoreCase(officialAccountsId) userInfos.put("officialAccountsId", StringUtil.isEmpty(officialAccountsId) || "undefined".equalsIgnoreCase(officialAccountsId)
|| "null".equalsIgnoreCase(officialAccountsId) ? null : Long.valueOf(officialAccountsId)); || "null".equalsIgnoreCase(officialAccountsId) ? null : NumberUtil.toLong(officialAccountsId));
} }
if (userInfoArry[i].contains("wechatUserId")) { if (userInfoArry[i].contains("wechatUserId")) {
String[] user = userInfoArry[i].split("="); String[] user = userInfoArry[i].split("=");
String wechatUserId = user[user.length - 1]; String wechatUserId = user[user.length - 1];
userInfos.put("wechatUserId", StringUtil.isEmpty(wechatUserId) || "undefined".equalsIgnoreCase(wechatUserId) userInfos.put("wechatUserId", StringUtil.isEmpty(wechatUserId) || "undefined".equalsIgnoreCase(wechatUserId)
|| "null".equalsIgnoreCase(wechatUserId) ? null : Long.valueOf(wechatUserId)); || "null".equalsIgnoreCase(wechatUserId) ? null : NumberUtil.toLong(wechatUserId));
} }
if (userInfoArry[i].contains("partyId")) { if (userInfoArry[i].contains("partyId")) {
String[] party = userInfoArry[i].split("="); String[] party = userInfoArry[i].split("=");
String partyId = party[party.length - 1]; String partyId = party[party.length - 1];
userInfos.put("partyId", StringUtil.isEmpty(partyId) || "undefined".equalsIgnoreCase(partyId) || "null".equalsIgnoreCase(partyId) userInfos.put("partyId", StringUtil.isEmpty(partyId) || "undefined".equalsIgnoreCase(partyId) || "null".equalsIgnoreCase(partyId)
? null : Long.valueOf(partyId)); ? null : NumberUtil.toLong(partyId));
} }
// editBy TC cookie里面需要带上顾问,systemCode,是否系统,场景值 // editBy TC cookie里面需要带上顾问,systemCode,是否系统,场景值
// modify by songx at 2017-05-17 如果值为undefined或者null直接跳过 // modify by songx at 2017-05-17 如果值为undefined或者null直接跳过
...@@ -151,7 +152,7 @@ public class Cookie { ...@@ -151,7 +152,7 @@ public class Cookie {
String[] adviser = userInfoArry[i].split("="); String[] adviser = userInfoArry[i].split("=");
String adviserId = adviser[adviser.length - 1]; String adviserId = adviser[adviser.length - 1];
userInfos.put("adviserId", StringUtil.isEmpty(adviserId) || "undefined".equalsIgnoreCase(adviserId) || "null".equalsIgnoreCase(adviserId) userInfos.put("adviserId", StringUtil.isEmpty(adviserId) || "undefined".equalsIgnoreCase(adviserId) || "null".equalsIgnoreCase(adviserId)
? null : Long.valueOf(adviserId)); ? null : NumberUtil.toLong(adviserId));
} }
if (userInfoArry[i].contains("systemCode")) { if (userInfoArry[i].contains("systemCode")) {
String[] systemCode = userInfoArry[i].split("="); String[] systemCode = userInfoArry[i].split("=");
...@@ -168,25 +169,25 @@ public class Cookie { ...@@ -168,25 +169,25 @@ public class Cookie {
String[] scene = userInfoArry[i].split("="); String[] scene = userInfoArry[i].split("=");
String sceneId = scene[scene.length - 1]; String sceneId = scene[scene.length - 1];
userInfos.put("sceneId", StringUtil.isEmpty(sceneId) || "undefined".equalsIgnoreCase(sceneId) || "null".equalsIgnoreCase(sceneId) ? null userInfos.put("sceneId", StringUtil.isEmpty(sceneId) || "undefined".equalsIgnoreCase(sceneId) || "null".equalsIgnoreCase(sceneId) ? null
: Long.valueOf(sceneId)); : NumberUtil.toLong(sceneId));
} }
if (userInfoArry[i].contains("userId")) { if (userInfoArry[i].contains("userId")) {
String[] userLogin = userInfoArry[i].split("="); String[] userLogin = userInfoArry[i].split("=");
String userId = userLogin[userLogin.length - 1]; String userId = userLogin[userLogin.length - 1];
userInfos.put("userId", StringUtil.isEmpty(userId) || "undefined".equalsIgnoreCase(userId) || "null".equalsIgnoreCase(userId) ? null userInfos.put("userId", StringUtil.isEmpty(userId) || "undefined".equalsIgnoreCase(userId) || "null".equalsIgnoreCase(userId) ? null
: Long.valueOf(userId)); : NumberUtil.toLong(userId));
} }
if (userInfoArry[i].contains("merchantMemberId")) { if (userInfoArry[i].contains("merchantMemberId")) {
String[] merchant = userInfoArry[i].split("="); String[] merchant = userInfoArry[i].split("=");
String merchantMemberId = merchant[merchant.length - 1]; String merchantMemberId = merchant[merchant.length - 1];
userInfos.put("merchantMemberId", StringUtil.isEmpty(merchantMemberId) || "undefined".equalsIgnoreCase(merchantMemberId) userInfos.put("merchantMemberId", StringUtil.isEmpty(merchantMemberId) || "undefined".equalsIgnoreCase(merchantMemberId)
|| "null".equalsIgnoreCase(merchantMemberId) ? null : Long.valueOf(merchantMemberId)); || "null".equalsIgnoreCase(merchantMemberId) ? null : NumberUtil.toLong(merchantMemberId));
} }
if (userInfoArry[i].contains("agentMemberId")) { if (userInfoArry[i].contains("agentMemberId")) {
String[] merchant = userInfoArry[i].split("="); String[] merchant = userInfoArry[i].split("=");
String agentMemberId = merchant[merchant.length - 1]; String agentMemberId = merchant[merchant.length - 1];
userInfos.put("agentMemberId", StringUtil.isEmpty(agentMemberId) || "undefined".equalsIgnoreCase(agentMemberId) userInfos.put("agentMemberId", StringUtil.isEmpty(agentMemberId) || "undefined".equalsIgnoreCase(agentMemberId)
|| "null".equalsIgnoreCase(agentMemberId) ? null : Long.valueOf(agentMemberId)); || "null".equalsIgnoreCase(agentMemberId) ? null : NumberUtil.toLong(agentMemberId));
} }
// add by gaop // add by gaop
if (userInfoArry[i].contains(PREVIEW_TYPE)) { if (userInfoArry[i].contains(PREVIEW_TYPE)) {
...@@ -205,13 +206,13 @@ public class Cookie { ...@@ -205,13 +206,13 @@ public class Cookie {
String[] firstTD = userInfoArry[i].split("="); String[] firstTD = userInfoArry[i].split("=");
String code = firstTD[firstTD.length - 1]; String code = firstTD[firstTD.length - 1];
userInfos.put(FIRST_TD, StringUtil.isEmpty(code) || "undefined".equalsIgnoreCase(code) || "null".equalsIgnoreCase(code) ? null userInfos.put(FIRST_TD, StringUtil.isEmpty(code) || "undefined".equalsIgnoreCase(code) || "null".equalsIgnoreCase(code) ? null
: Long.valueOf(code)); : NumberUtil.toLong(code));
} }
if (userInfoArry[i].contains(SECOND_TD)) { if (userInfoArry[i].contains(SECOND_TD)) {
String[] secondTD = userInfoArry[i].split("="); String[] secondTD = userInfoArry[i].split("=");
String code = secondTD[secondTD.length - 1]; String code = secondTD[secondTD.length - 1];
userInfos.put(SECOND_TD, StringUtil.isEmpty(code) || "undefined".equalsIgnoreCase(code) || "null".equalsIgnoreCase(code) ? null userInfos.put(SECOND_TD, StringUtil.isEmpty(code) || "undefined".equalsIgnoreCase(code) || "null".equalsIgnoreCase(code) ? null
: Long.valueOf(code)); : NumberUtil.toLong(code));
} }
} }
return userInfos; return userInfos;
...@@ -226,7 +227,7 @@ public class Cookie { ...@@ -226,7 +227,7 @@ public class Cookie {
*/ */
public static Long getId(String userInfo, String type) throws BizException { public static Long getId(String userInfo, String type) throws BizException {
String value = getString(userInfo, type); String value = getString(userInfo, type);
return StringUtil.isEmpty(value) || "undefined".equalsIgnoreCase(value) || "null".equalsIgnoreCase(value) ? null : Long.valueOf(value); return StringUtil.isEmpty(value) || "undefined".equalsIgnoreCase(value) || "null".equalsIgnoreCase(value) ? null : NumberUtil.toLong(value);
} }
/** /**
......
...@@ -127,6 +127,47 @@ public class WordDataExportor { ...@@ -127,6 +127,47 @@ public class WordDataExportor {
} }
/** /**
* 生成word
* @param dataMap
* @param templateName
* @return
* @author linweibin
* @date 2017年5月22日 下午5:22:38
*/
@SuppressWarnings("deprecation")
public static void generateWord(Class clazz, Map<String, Object> dataMap, String templateName, File tmpdir, String fileName) {
logger.info("开始生成word+++");
try {
// 创建配置实例
Configuration configuration = new Configuration();
// 设置编码
configuration.setDefaultEncoding("UTF-8");
// 获取template文件路径
configuration.setClassForTemplateLoading(clazz, "/template");
// 获取模板
Template template = configuration.getTemplate(templateName);
// 输出文件
File outFile = new File(tmpdir, fileName);
// 将模板和数据模型合并生成文件
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
// 生成文件
template.process(dataMap, out);
logger.info("生成word+++成功");
// 关闭流
out.flush();
out.close();
} catch (Exception e) {
logger.error("生成word异常+++" + e.getMessage(), e);
}
}
/**
* 生成随机文件名 * 生成随机文件名
* @return * @return
* @author linweibin * @author linweibin
......
package com.pcloud.common.utils.httpclient; package com.pcloud.common.utils.httpclient;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.pcloud.common.utils.rsa.MD5; import com.pcloud.common.utils.rsa.MD5;
import com.pcloud.common.utils.string.StringUtil; import com.pcloud.common.utils.string.StringUtil;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
/** /**
* @author:songx * @author:songx
* @date:2017年12月4日,下午4:58:39 * @date:2017年12月4日,下午4:58:39
*/ */
public class UrlUtils { public class UrlUtils {
/** /**
* *
*/ */
private static final Logger LOGGER = LoggerFactory.getLogger(UrlUtils.class); private static final Logger LOGGER = LoggerFactory.getLogger(UrlUtils.class);
/** /**
* 请求地址(新郎接口) * 请求地址(新郎接口)
*/ */
private static final String REQUEST_URL = "https://api.weibo.com/2/short_url/shorten.json?source=1681459862&url_long="; private static final String REQUEST_URL = "https://api.weibo.com/2/short_url/shorten.json?source=1681459862&url_long=";
/** /**
* 请求地址(OWN) * 请求地址(OWN)
*/ */
private static final String REQUEST_URL2 = "https://rays.5rs.me/convert/v1.0/url/shorten"; private static final String REQUEST_URL2 = "https://rays.5rs.me/convert/v1.0/url/shorten";
/** /**
* 获取短链接(新浪) * 自定义生成 MD5 加密字符传前的混合 KEY
* */
* @param long_url public static final String PRIVATE_KEY = "lgsc1205";
* @return
*/ /**
public static String getShortUrl(String long_url) { * 获取短链接(新浪)
String result = callHttp(long_url); *
if (StringUtil.isEmpty(result)) { * @param long_url
return null; * @return
} */
JSONObject resultObject = JSONObject.parseObject(result); public static String getShortUrl(String long_url) {
JSONArray array = resultObject.getJSONArray("urls"); String result = callHttp(long_url);
JSONObject object = array.getJSONObject(0); if (StringUtil.isEmpty(result)) {
return object.getString("url_short"); return null;
} }
JSONObject resultObject = JSONObject.parseObject(result);
/** JSONArray array = resultObject.getJSONArray("urls");
* 发送请求(新浪) JSONObject object = array.getJSONObject(0);
* return object.getString("url_short");
* @param long_url }
* @return
*/ /**
private static String callHttp(String long_url) { * 发送请求(新浪)
LOGGER.info("【URL】短链接转换(新浪),<START>.[long_url]=" + long_url); *
CloseableHttpClient httpclient = HttpClients.createDefault(); * @param long_url
HttpGet httpGet = new HttpGet(REQUEST_URL + long_url); * @return
String resContent = null; */
try { private static String callHttp(String long_url) {
CloseableHttpResponse response = httpclient.execute(httpGet); LOGGER.info("【URL】短链接转换(新浪),<START>.[long_url]=" + long_url);
// 获取响应实体 CloseableHttpClient httpclient = HttpClients.createDefault();
HttpEntity entity = response.getEntity(); HttpGet httpGet = new HttpGet(REQUEST_URL + long_url);
if (entity != null) { String resContent = null;
resContent = EntityUtils.toString(entity); try {
} CloseableHttpResponse response = httpclient.execute(httpGet);
} catch (IOException e) { // 获取响应实体
LOGGER.error("【URL】短链接转换失败(新浪):" + e.getMessage(), e); HttpEntity entity = response.getEntity();
} if (entity != null) {
LOGGER.info("【URL】短链接转换(新浪),<END>.[resContent]=" + resContent); resContent = EntityUtils.toString(entity);
return resContent; }
} } catch (IOException e) {
LOGGER.error("【URL】短链接转换失败(新浪):" + e.getMessage(), e);
/** }
* 获取短链接(OWN) LOGGER.info("【URL】短链接转换(新浪),<END>.[resContent]=" + resContent);
* return resContent;
* @param long_url }
* @return
*/ /**
public static String getShortUrl4Own(String long_url) { * 获取短链接(OWN)
String result = callHttp4Own(long_url); *
if (StringUtil.isEmpty(result)) { * @param long_url
return null; * @return
} */
JSONObject resultObject = JSONObject.parseObject(result); public static String getShortUrl4Own(String long_url) {
JSONObject dataObject = resultObject.getJSONObject("data"); String result = callHttp4Own(long_url);
return dataObject == null ? null : dataObject.getString("shortUrl"); if (StringUtil.isEmpty(result)) {
} return null;
}
/** JSONObject resultObject = JSONObject.parseObject(result);
* 发送请求(OWN) JSONObject dataObject = resultObject.getJSONObject("data");
* return dataObject == null ? null : dataObject.getString("shortUrl");
* @param long_url }
* @return
*/ /**
private static String callHttp4Own(String long_url) { * 发送请求(OWN)
LOGGER.info("【URL】短链接转换(OWN),<START>.[long_url]=" + long_url); *
if (StringUtil.isEmpty(long_url)) { * @param long_url
return null; * @return
} */
CloseableHttpClient httpclient = HttpClients.createDefault(); private static String callHttp4Own(String long_url) {
HttpPost httpPost = new HttpPost(REQUEST_URL2); LOGGER.info("【URL】短链接转换(OWN),<START>.[long_url]=" + long_url);
String resContent = null; if (StringUtil.isEmpty(long_url)) {
try { return null;
//设置参数到请求对象中 }
JSONObject jsonObject = new JSONObject(); CloseableHttpClient httpclient = HttpClients.createDefault();
jsonObject.put("originUrl", long_url); HttpPost httpPost = new HttpPost(REQUEST_URL2);
StringEntity stringEntity = new StringEntity(jsonObject.toJSONString(), Charset.forName("UTF-8")); String resContent = null;
httpPost.setEntity(stringEntity); try {
//设置header信息 // 设置参数到请求对象中
//指定报文头【Content-type】、【User-Agent】 JSONObject jsonObject = new JSONObject();
httpPost.setHeader("Content-type", "application/json;charset=UTF-8"); jsonObject.put("originUrl", long_url);
CloseableHttpResponse response = httpclient.execute(httpPost); StringEntity stringEntity = new StringEntity(jsonObject.toJSONString(), Charset.forName("UTF-8"));
// 获取响应实体 httpPost.setEntity(stringEntity);
HttpEntity entity = response.getEntity(); // 设置header信息
if (entity != null) { // 指定报文头【Content-type】、【User-Agent】
resContent = EntityUtils.toString(entity); httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
} CloseableHttpResponse response = httpclient.execute(httpPost);
} catch (IOException e) { // 获取响应实体
LOGGER.error("【URL】短链接转换失败(OWN):" + e.getMessage(), e); HttpEntity entity = response.getEntity();
} if (entity != null) {
LOGGER.info("【URL】短链接转换(OWN),<END>.[resContent]=" + resContent); resContent = EntityUtils.toString(entity);
return resContent; }
} } catch (IOException e) {
LOGGER.error("【URL】短链接转换失败(OWN):" + e.getMessage(), e);
/** }
* 缩短链接 LOGGER.info("【URL】短链接转换(OWN),<END>.[resContent]=" + resContent);
* return resContent;
* @param url }
* @return
*/ /**
public static String[] shortenUrl(String url) { * 对传入的链接进行加密
// 可以自定义生成 MD5 加密字符传前的混合 KEY *
String key = "lgsc1205"; * @param url
// 要使用生成 URL 的字符 * @return
String[] chars = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", */
"q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", public static String[] shortenUrl(String url) {
"B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", // 对传入网址进行 MD5 加密
"W", "X", "Y", "Z" String hex = MD5.getMD5Str(PRIVATE_KEY + url);
return shortenUrlMd5(hex);
}; }
// 对传入网址进行 MD5 加密
String hex = MD5.getMD5Str(key + url); /**
* 缩短链接
String[] resUrl = new String[4]; *
for (int i = 0; i < 4; i++) { * @param url
* @return
// 把加密字符按照 8 位一组 16 进制与 0x3FFFFFFF 进行位与运算 */
String sTempSubString = hex.substring(i * 8, i * 8 + 8); public static String[] shortenUrlMd5(String hex) {
// 要使用生成 URL 的字符
// 这里需要使用 long 型来转换,因为 Inteper .parseInt() 只能处理 31 位 , 首位为符号位 , String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
// 如果不用long ,则会越界 "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16); "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
String outChars = ""; "W", "X", "Y", "Z" };
for (int j = 0; j < 7; j++) {
// 把得到的值与 0x0000003D 进行位与运算,取得字符数组 chars 索引 String[] resUrl = new String[4];
long index = 0x0000003D & lHexLong; for (int i = 0; i < 4; i++) {
// 把取得的字符相加 // 把加密字符按照 8 位一组 16 进制与 0x3FFFFFFF 进行位与运算
outChars += chars[(int) index]; String sTempSubString = hex.substring(i * 8, i * 8 + 8);
// 每次循环按位右移 4 位
lHexLong = lHexLong >> 4; // 这里需要使用 long 型来转换,因为 Inteper .parseInt() 只能处理 31 位 , 首位为符号位 ,
} // 如果不用long ,则会越界
// 把字符串存入对应索引的输出数组 long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16);
resUrl[i] = outChars; String outChars = "";
} for (int j = 0; j < 7; j++) {
return resUrl; // 把得到的值与 0x0000003D 进行位与运算,取得字符数组 chars 索引
} long index = 0x0000003D & lHexLong;
// 把取得的字符相加
} outChars += chars[(int) index];
// 每次循环按位右移 4 位
lHexLong = lHexLong >> 4;
}
// 把字符串存入对应索引的输出数组
resUrl[i] = outChars;
}
return resUrl;
}
}
...@@ -10,8 +10,6 @@ import org.slf4j.LoggerFactory; ...@@ -10,8 +10,6 @@ import org.slf4j.LoggerFactory;
import com.pcloud.common.utils.string.StringUtil; import com.pcloud.common.utils.string.StringUtil;
/** /**
* MD5 * MD5
*/ */
...@@ -66,9 +64,22 @@ public class MD5 { ...@@ -66,9 +64,22 @@ public class MD5 {
else else
md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
} }
return md5StrBuff.toString().toUpperCase(); return md5StrBuff.toString();
} }
/**
* MD5字符串,全大写
*
* @param str
* @return
*/
public static String getMD5StrUpper(String str) {
if (StringUtil.isEmpty(str)) {
return str;
}
return getMD5Str(str).toUpperCase();
}
/** /**
* MD5字符串,全小写 * MD5字符串,全小写
* *
...@@ -111,9 +122,9 @@ public class MD5 { ...@@ -111,9 +122,9 @@ public class MD5 {
return md5StrBuff.toString().toUpperCase(); return md5StrBuff.toString().toUpperCase();
} }
public static void main(String[] args){ public static void main(String[] args) {
System.out.println(MD5.getMD5Str("chenjianhua")); System.out.println(MD5.getMD5Str("chenjianhua"));
System.out.println(DigestUtils.md5Hex("chenjianhua").toUpperCase()); System.out.println(DigestUtils.md5Hex("chenjianhua").toUpperCase());
} }
} }
...@@ -613,7 +613,26 @@ public class StringTools { ...@@ -613,7 +613,26 @@ public class StringTools {
* @param array * @param array
* @return * @return
*/ */
public static boolean equalss(String str, String[] array) { public static boolean equalss(String str, String... array) {
if (StringUtil.isEmpty(str) || array == null) {
return false;
}
for (String s : array) {
if (str.equals(s)) {
return true;
}
}
return false;
}
/**
* 判断字符是否在数组中存在。如果数组为null则返回false
*
* @param str
* @param array
* @return
*/
public static boolean equalss(String str, List<String> array) {
if (StringUtil.isEmpty(str) || array == null) { if (StringUtil.isEmpty(str) || array == null) {
return false; return false;
} }
......
...@@ -120,8 +120,8 @@ public class CompressUtils { ...@@ -120,8 +120,8 @@ public class CompressUtils {
if (ListUtils.isEmpty(fileUrlList)) { if (ListUtils.isEmpty(fileUrlList)) {
return null; return null;
} }
zipName = FileUtils.formatName(zipName); String zipNameFormat = FileUtils.formatName(zipName);
String tempZipName = zipName + "_" + LocalDateUtils.getYmdhmss(); String tempZipName = zipNameFormat + "_" + LocalDateUtils.getYmdhmss();
String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip"; String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip";
// 检查临时文件夹是否存在,不存在就创建 // 检查临时文件夹是否存在,不存在就创建
String fileFolderPath = FILE_LOCAL_PATH + tempZipName; String fileFolderPath = FILE_LOCAL_PATH + tempZipName;
...@@ -141,7 +141,7 @@ public class CompressUtils { ...@@ -141,7 +141,7 @@ public class CompressUtils {
FileUtils.isDir(ZIP_FILE_PATH); FileUtils.isDir(ZIP_FILE_PATH);
CompressUtils.zip(fileFolderPath, zipFilePath); CompressUtils.zip(fileFolderPath, zipFilePath);
// 上传文件到服务器中 // 上传文件到服务器中
uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipName); uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipNameFormat);
uploadResultInfo.setFileName(zipName); uploadResultInfo.setFileName(zipName);
} catch (Exception e) { } catch (Exception e) {
LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e); LOGGER.error("【压缩】压缩失败,<ERROR>:" + e.getMessage(), e);
......
/**
*
*/
package com.pcloud.common.vo;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
/**
* VO父类
*
* @author:songx
* @date:2019年1月14日,下午8:53:01
*/
@JsonInclude(value = Include.NON_NULL)
public class BaseVO implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5943734920212204836L;
}
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>
<parent>
<groupId>com.pcloud.common</groupId>
<artifactId>pcloud-common-parent</artifactId>
<version>2.1.0-SNAPSHOT</version>
</parent>
<artifactId>pcloud-solr</artifactId>
<packaging>jar</packaging>
<version>${pcloud-solr.version}</version>
<name>pcloud-solr</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.pcloud.common</groupId>
<artifactId>pcloud-common-config</artifactId>
<version>${pcloud-common-config.version}</version>
</dependency>
<!-- solr add by gaop at 2018-4-23 11:33:47 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
<version>${spring.data.solr.version}</version>
</dependency>
<!-- Spring Cloud Begin -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- Spring Cloud End -->
<!-- Common Dependency Begin -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.18</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.38</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
<!-- Common Dependency End -->
</dependencies>
</project>
package com.pcloud.common.utils.solr; package com.pcloud.solr;
import java.io.Serializable; import java.io.Serializable;
import java.util.Calendar; import java.util.Calendar;
......
package com.pcloud.common.utils.solr; package com.pcloud.solr;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
......
package com.pcloud.common.utils.solr; package com.pcloud.solr;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
...@@ -8,7 +8,7 @@ import java.util.List; ...@@ -8,7 +8,7 @@ import java.util.List;
* @author PENG * @author PENG
* @date 2018/4/24 * @date 2018/4/24
*/ */
public class SolrResult implements Serializable { public class SolrResult<T> implements Serializable {
private static final long serialVersionUID = 1195918725820896691L; private static final long serialVersionUID = 1195918725820896691L;
...@@ -25,7 +25,7 @@ public class SolrResult implements Serializable { ...@@ -25,7 +25,7 @@ public class SolrResult implements Serializable {
/** /**
* 查询结果列表 * 查询结果列表
*/ */
private List<SolrDto> list; private List<T> list;
public Integer getTotalCount() { public Integer getTotalCount() {
return totalCount; return totalCount;
...@@ -43,11 +43,11 @@ public class SolrResult implements Serializable { ...@@ -43,11 +43,11 @@ public class SolrResult implements Serializable {
this.maxScore = maxScore; this.maxScore = maxScore;
} }
public List<SolrDto> getList() { public List<T> getList() {
return list; return list;
} }
public void setList(List<SolrDto> list) { public void setList(List<T> list) {
this.list = list; this.list = list;
} }
......
package com.pcloud.common.utils.solr; package com.pcloud.solr;
import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.apache.commons.collections.MapUtils; import org.apache.commons.collections4.MapUtils;
import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.CloudSolrClient; import org.apache.solr.client.solrj.impl.CloudSolrClient;
...@@ -21,8 +23,6 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -21,8 +23,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
/** /**
* Description solr全文检索工具类 * Description solr全文检索工具类
...@@ -39,7 +39,7 @@ public class SolrUtils { ...@@ -39,7 +39,7 @@ public class SolrUtils {
private static String defaultCollection; private static String defaultCollection;
private static CloudSolrClient solrClient; protected static CloudSolrClient solrClient;
/** /**
* 新增或修改索引(id主键存在时为更新) * 新增或修改索引(id主键存在时为更新)
...@@ -52,6 +52,15 @@ public class SolrUtils { ...@@ -52,6 +52,15 @@ public class SolrUtils {
/** /**
* 新增或修改索引(id主键存在时为更新) * 新增或修改索引(id主键存在时为更新)
* @param object solr索引DTO
* @return 是否成功
*/
public static Boolean addObject(Object object) {
return addObject(getDefaultCollection(), object);
}
/**
* 新增或修改索引(id主键存在时为更新)
* @param collection 索引集 * @param collection 索引集
* @param solrDto solr索引DTO * @param solrDto solr索引DTO
* @return 是否成功 * @return 是否成功
...@@ -68,6 +77,23 @@ public class SolrUtils { ...@@ -68,6 +77,23 @@ public class SolrUtils {
} }
/** /**
* 新增或修改索引(id主键存在时为更新)
* @param collection 索引集
* @param object solr索引DTO
* @return 是否成功
*/
public static Boolean addObject(String collection, Object object) {
try {
solrClient.addBean(collection, object);
solrClient.commit(collection);
} catch (Exception e) {
LOGGER.error("solr新增索引失败:" + e.getMessage(), e);
return false;
}
return true;
}
/**
* 批量新增或修改索引(id主键存在时为更新) * 批量新增或修改索引(id主键存在时为更新)
* @param list solr索引DTO列表 * @param list solr索引DTO列表
* @return 是否成功 * @return 是否成功
...@@ -78,6 +104,15 @@ public class SolrUtils { ...@@ -78,6 +104,15 @@ public class SolrUtils {
/** /**
* 批量新增或修改索引(id主键存在时为更新) * 批量新增或修改索引(id主键存在时为更新)
* @param list solr索引DTO列表
* @return 是否成功
*/
public static Boolean addObject(List<Object> list) {
return addObject(getDefaultCollection(), list);
}
/**
* 批量新增或修改索引(id主键存在时为更新)
* @param collection 索引集 * @param collection 索引集
* @param list solr索引DTO列表 * @param list solr索引DTO列表
* @return 是否成功 * @return 是否成功
...@@ -94,6 +129,23 @@ public class SolrUtils { ...@@ -94,6 +129,23 @@ public class SolrUtils {
} }
/** /**
* 批量新增或修改索引(id主键存在时为更新)
* @param collection 索引集
* @param list solr索引DTO列表
* @return 是否成功
*/
public static Boolean addObject(String collection, List<SolrDto> list) {
try {
solrClient.addBeans(collection, list);
solrClient.commit(collection);
} catch (Exception e) {
LOGGER.error("solr批量新增索引失败:" + e.getMessage(), e);
return false;
}
return true;
}
/**
* 根据id主键删除索引 * 根据id主键删除索引
* @param id id主键 * @param id id主键
* @return 是否成功 * @return 是否成功
...@@ -156,6 +208,15 @@ public class SolrUtils { ...@@ -156,6 +208,15 @@ public class SolrUtils {
/** /**
* 根据id主键获取索引 * 根据id主键获取索引
* @param id id主键
* @return SolrDto
*/
public static SolrDocument getObjectById(String id) {
return getObjectById(getDefaultCollection(), id);
}
/**
* 根据id主键获取索引
* @param collection 索引集 * @param collection 索引集
* @param id id主键 * @param id id主键
* @return SolrDto * @return SolrDto
...@@ -175,6 +236,21 @@ public class SolrUtils { ...@@ -175,6 +236,21 @@ public class SolrUtils {
} }
/** /**
* 根据id主键获取索引
* @param collection 索引集
* @param id id主键
* @return SolrDto
*/
public static SolrDocument getObjectById(String collection, String id) {
try {
return solrClient.getById(collection, id);
} catch (Exception e) {
LOGGER.error("solr根据id查询索引失败:" + e.getMessage(), e);
return null;
}
}
/**
* 根据id主键列表批量获取索引 * 根据id主键列表批量获取索引
* @param ids id主键列表 * @param ids id主键列表
* @return SolrDto Map * @return SolrDto Map
...@@ -185,13 +261,22 @@ public class SolrUtils { ...@@ -185,13 +261,22 @@ public class SolrUtils {
/** /**
* 根据id主键列表批量获取索引 * 根据id主键列表批量获取索引
* @param ids id主键列表
* @return SolrDto Map
*/
public static Map<String, SolrDocument> mapObjectByIds(List<String> ids) {
return mapObjectByIds(getDefaultCollection(), ids);
}
/**
* 根据id主键列表批量获取索引
* @param collection 索引集 * @param collection 索引集
* @param ids id主键列表 * @param ids id主键列表
* @return SolrDto Map * @return SolrDto Map
*/ */
public static Map<String, SolrDto> getById(String collection, List<String> ids) { public static Map<String, SolrDto> getById(String collection, List<String> ids) {
try { try {
if (ListUtils.isEmpty(ids)) { if (null == ids || ids.isEmpty()) {
return null; return null;
} }
SolrDocumentList documents = solrClient.getById(collection, ids); SolrDocumentList documents = solrClient.getById(collection, ids);
...@@ -211,6 +296,33 @@ public class SolrUtils { ...@@ -211,6 +296,33 @@ public class SolrUtils {
} }
/** /**
* 根据id主键列表批量获取索引
* @param collection 索引集
* @param ids id主键列表
* @return SolrDto Map
*/
public static Map<String, SolrDocument> mapObjectByIds(String collection, List<String> ids) {
try {
if (null == ids || ids.isEmpty()) {
return null;
}
SolrDocumentList documents = solrClient.getById(collection, ids);
if (null != documents) {
Map<String, SolrDocument> map = new HashMap<>();
for (SolrDocument document : documents) {
map.put((String) document.get("id"), document);
}
return map;
} else {
return null;
}
} catch (Exception e) {
LOGGER.error("solr根据id批量查询索引失败:" + e.getMessage(), e);
return null;
}
}
/**
* 查询 * 查询
* @param param 查询参数 * @param param 查询参数
* @return SolrResult * @return SolrResult
...@@ -221,18 +333,27 @@ public class SolrUtils { ...@@ -221,18 +333,27 @@ public class SolrUtils {
/** /**
* 查询 * 查询
* @param param 查询参数
* @return SolrResult
*/
public static SolrResult<SolrDocument> searchObject(SolrQueryParam param) {
return searchObject(getDefaultCollection(), param);
}
/**
* 查询
* @param collection 索引集 * @param collection 索引集
* @param param 查询参数 * @param param 查询参数
* @return SolrResult * @return SolrResult
*/ */
public static SolrResult search(String collection, SolrQueryParam param) { public static SolrResult<SolrDto> search(String collection, SolrQueryParam param) {
try { try {
SolrQuery solrQuery = formatQueryParam(param); SolrQuery solrQuery = formatQueryParam(param);
solrQuery.set("wt", "json"); solrQuery.set("wt", "json");
QueryResponse response = solrClient.query(collection, solrQuery); QueryResponse response = solrClient.query(collection, solrQuery);
SolrDocumentList documents = response.getResults(); SolrDocumentList documents = response.getResults();
LOGGER.info("solr查询结果:" + documents.toString()); LOGGER.info("solr查询结果:" + documents.toString());
SolrResult solrResult = new SolrResult(); SolrResult<SolrDto> solrResult = new SolrResult<SolrDto>();
solrResult.setTotalCount(Integer.parseInt(documents.getNumFound() + "")); solrResult.setTotalCount(Integer.parseInt(documents.getNumFound() + ""));
solrResult.setMaxScore(documents.getMaxScore()); solrResult.setMaxScore(documents.getMaxScore());
List<SolrDto> list = new ArrayList<>(); List<SolrDto> list = new ArrayList<>();
...@@ -249,6 +370,34 @@ public class SolrUtils { ...@@ -249,6 +370,34 @@ public class SolrUtils {
} }
/** /**
* 查询
* @param collection 索引集
* @param param 查询参数
* @return SolrResult
*/
public static SolrResult<SolrDocument> searchObject(String collection, SolrQueryParam param) {
try {
SolrQuery solrQuery = formatQueryParam(param);
solrQuery.set("wt", "json");
QueryResponse response = solrClient.query(collection, solrQuery);
SolrDocumentList documents = response.getResults();
LOGGER.info("solr查询结果:" + documents.toString());
SolrResult<SolrDocument> solrResult = new SolrResult<>();
solrResult.setTotalCount(Integer.parseInt(documents.getNumFound() + ""));
solrResult.setMaxScore(documents.getMaxScore());
List<SolrDocument> list = new ArrayList<>();
for (SolrDocument document : documents) {
list.add(document);
}
solrResult.setList(list);
return solrResult;
} catch (Exception e) {
LOGGER.error("solr查询索引失败:" + e.getMessage(), e);
return null;
}
}
/**
* 将solr返回的document转换成solrDto * 将solr返回的document转换成solrDto
* @param document solr文档 * @param document solr文档
* @return SolrDto * @return SolrDto
...@@ -287,7 +436,7 @@ public class SolrUtils { ...@@ -287,7 +436,7 @@ public class SolrUtils {
* @param param solr查询参数 * @param param solr查询参数
* @return SolrQuery * @return SolrQuery
*/ */
private static SolrQuery formatQueryParam(SolrQueryParam param) { protected static SolrQuery formatQueryParam(SolrQueryParam param) {
SolrQuery solrQuery = new SolrQuery(); SolrQuery solrQuery = new SolrQuery();
if (null == param) { if (null == param) {
param = new SolrQueryParam(); param = new SolrQueryParam();
...@@ -297,7 +446,7 @@ public class SolrUtils { ...@@ -297,7 +446,7 @@ public class SolrUtils {
} else { } else {
solrQuery.set("q", "*:*"); solrQuery.set("q", "*:*");
} }
if (!ListUtils.isEmpty(param.getFq())) { if (null != param.getFq() && !param.getFq().isEmpty()) {
for (String fq : param.getFq()) { for (String fq : param.getFq()) {
solrQuery.addFilterQuery(fq); solrQuery.addFilterQuery(fq);
} }
...@@ -353,7 +502,7 @@ public class SolrUtils { ...@@ -353,7 +502,7 @@ public class SolrUtils {
*/ */
public static String getUTCShortDateStr() { public static String getUTCShortDateStr() {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(DateUtils.dateFormat(new Date())); calendar.setTime(dateFormat(new Date()));
calendar.add(Calendar.HOUR_OF_DAY, -8); calendar.add(Calendar.HOUR_OF_DAY, -8);
return UTC_FULL_DATE_FORMAT.format(calendar.getTime()); return UTC_FULL_DATE_FORMAT.format(calendar.getTime());
} }
...@@ -365,15 +514,31 @@ public class SolrUtils { ...@@ -365,15 +514,31 @@ public class SolrUtils {
*/ */
public static String formatUTCShortDate(Date date) { public static String formatUTCShortDate(Date date) {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTime(DateUtils.dateFormat(date)); calendar.setTime(dateFormat(date));
calendar.add(Calendar.HOUR_OF_DAY, -8); calendar.add(Calendar.HOUR_OF_DAY, -8);
return UTC_FULL_DATE_FORMAT.format(calendar.getTime()); return UTC_FULL_DATE_FORMAT.format(calendar.getTime());
} }
/** /**
* 对时间进行格式化
* @param date 时间
* @return 格式化时间
*/
protected static Date dateFormat(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date value = new Date();
try {
value = format.parse(format.format(date));
} catch (ParseException e) {
LOGGER.error("日期转换错误:" + e.getMessage(), e);
}
return value;
}
/**
* 获取默认集合 * 获取默认集合
*/ */
private static String getDefaultCollection() { protected static String getDefaultCollection() {
return null == solrClient.getDefaultCollection() ? defaultCollection : solrClient.getDefaultCollection(); return null == solrClient.getDefaultCollection() ? defaultCollection : solrClient.getDefaultCollection();
} }
......
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
<module>pcloud-common-config</module> <module>pcloud-common-config</module>
<module>pcloud-common</module> <module>pcloud-common</module>
<module>pcloud-common-core</module> <module>pcloud-common-core</module>
<module>pcloud-solr</module>
</modules> </modules>
<packaging>pom</packaging> <packaging>pom</packaging>
...@@ -47,6 +48,7 @@ ...@@ -47,6 +48,7 @@
<pcloud-common.version>2.1.0-RELEASE</pcloud-common.version> <pcloud-common.version>2.1.0-RELEASE</pcloud-common.version>
<pcloud-common-config.version>2.1.0-RELEASE</pcloud-common-config.version> <pcloud-common-config.version>2.1.0-RELEASE</pcloud-common-config.version>
<pcloud-common-core.version>2.1.0-RELEASE</pcloud-common-core.version> <pcloud-common-core.version>2.1.0-RELEASE</pcloud-common-core.version>
<pcloud-solr.version>2.1.0-RELEASE</pcloud-solr.version>
</properties> </properties>
</profile> </profile>
<!-- 压测环境 --> <!-- 压测环境 -->
...@@ -68,6 +70,7 @@ ...@@ -68,6 +70,7 @@
<pcloud-common.version>2.1.0-RELEASE</pcloud-common.version> <pcloud-common.version>2.1.0-RELEASE</pcloud-common.version>
<pcloud-common-config.version>2.1.0-RELEASE</pcloud-common-config.version> <pcloud-common-config.version>2.1.0-RELEASE</pcloud-common-config.version>
<pcloud-common-core.version>2.1.0-RELEASE</pcloud-common-core.version> <pcloud-common-core.version>2.1.0-RELEASE</pcloud-common-core.version>
<pcloud-solr.version>2.1.0-RELEASE</pcloud-solr.version>
</properties> </properties>
</profile> </profile>
<!-- 生产环境 RAYS --> <!-- 生产环境 RAYS -->
...@@ -89,6 +92,7 @@ ...@@ -89,6 +92,7 @@
<pcloud-common.version>2.1.1-RELEASE</pcloud-common.version> <pcloud-common.version>2.1.1-RELEASE</pcloud-common.version>
<pcloud-common-config.version>2.1.1-RELEASE</pcloud-common-config.version> <pcloud-common-config.version>2.1.1-RELEASE</pcloud-common-config.version>
<pcloud-common-core.version>2.1.1-RELEASE</pcloud-common-core.version> <pcloud-common-core.version>2.1.1-RELEASE</pcloud-common-core.version>
<pcloud-solr.version>2.1.1-RELEASE</pcloud-solr.version>
</properties> </properties>
</profile> </profile>
</profiles> </profiles>
...@@ -227,6 +231,11 @@ ...@@ -227,6 +231,11 @@
<version>4.4.6</version> <version>4.4.6</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId> <groupId>redis.clients</groupId>
<artifactId>jedis</artifactId> <artifactId>jedis</artifactId>
<version>2.9.0</version> <version>2.9.0</version>
...@@ -303,13 +312,6 @@ ...@@ -303,13 +312,6 @@
</dependency> </dependency>
<!-- end --> <!-- end -->
<!-- solr add by gaop at 2018-4-23 11:33:47 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
<version>${spring.data.solr.version}</version>
</dependency>
<!-- Jackson Begin --> <!-- Jackson Begin -->
<dependency> <dependency>
<groupId>org.codehaus.jackson</groupId> <groupId>org.codehaus.jackson</groupId>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment