Commit 957ac6e5 by shuyunhu
parents 3d06297f 302789f6
......@@ -10,9 +10,26 @@ spring:
loadbalancer:
retry:
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:
influx:
uri: http://192.168.83.241:8086/write
uri: http://192.168.89.200:8086/write
step: PT10S
db: ${spring.application.name}
enabled: true
......@@ -32,7 +49,7 @@ spring:
retry:
max-attempts: 3 # 最大重试次数
enabled: true # 是否开启消费者重试(为false时关闭消费者重试,这时消费端代码异常会一直重复收到消息)
initial-interval: 5000 # 重试间隔时间(单位毫秒)
initial-interval: 300000 # 重试间隔时间(单位毫秒)
default-requeue-rejected: true # 重试次数超过上面的设置之后是否丢弃(false不丢弃时需要写相应代码将该消息加入死信队列)
data:
solr:
......
......@@ -86,4 +86,6 @@ uedThirdPartyOrderUrl=https://rayscloud.chubanyun.net
## \u7CFB\u7EDF\u73AF\u5883
system.env = pro
jsbj.agent.id = 1000009100
\ No newline at end of file
jsbj.agent.id = 1000009100
product.parentTutor.proLabelId = 7461
\ No newline at end of file
......@@ -10,9 +10,26 @@ spring:
loadbalancer:
retry:
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:
influx:
uri: http://192.168.83.241:8086/write
uri: http://192.168.89.200:8086/write
step: PT10S
db: ${spring.application.name}
enabled: false
......@@ -32,7 +49,7 @@ spring:
retry:
max-attempts: 3 # 最大重试次数
enabled: true # 是否开启消费者重试(为false时关闭消费者重试,这时消费端代码异常会一直重复收到消息)
initial-interval: 5000 # 重试间隔时间(单位毫秒)
initial-interval: 300000 # 重试间隔时间(单位毫秒)
default-requeue-rejected: true # 重试次数超过上面的设置之后是否丢弃(false不丢弃时需要写相应代码将该消息加入死信队列)
data:
solr:
......
......@@ -88,4 +88,6 @@ uedThirdPartyOrderUrl=http://deveapi.chubanyun.net
## \u7CFB\u7EDF\u73AF\u5883
system.env = uat
jsbj.agent.id = 12829
\ No newline at end of file
jsbj.agent.id = 12829
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 {
/**
* 打卡
*/
CLOCK("clock");
CLOCK("clock"),
/**
* 伴读魔法箱
*/
AUDIO_MAGIC("magic");
......
......@@ -85,15 +85,20 @@ public enum ConvertEnum {
*/
AUDIO_LESSON("AUDIO_LESSON"),
/**
* 音频纯听
*/
AUDIO_LISTEN("AUDIO_LISTEN");
/**
* 值
*/
public final String value;
/**
* 音频纯听
*/
AUDIO_LISTEN("AUDIO_LISTEN"),
/**
* 音频魔法箱
*/
AUDIO_MAGIC("AUDIO_MAGIC");
/**
* 值
*/
public final String value;
/**
* 构造
......
......@@ -16,6 +16,11 @@ public class MQQueueConstant {
public static final String TEMPLATE = "templateQueue";
/**
* 音频配音(MP3)
*/
public static final String DUBBING = "dubbingQueue";
/**
* 文件转码(PDF、OFFICE)
*/
public static final String TRANSCODE = "transcodeQueue";
......@@ -86,6 +91,11 @@ public class MQQueueConstant {
public static final String CONVERT_TO_AUDIOLESSON = "convert2AudioLessonQueue";
/**
* 文件转码结束(音视频)->音频课/纯听
*/
public static final String CONVERT_TO_AUDIOMAGIC = "convert2AudioMagicQueue";
/**
* 数据埋点
*/
public static final String FRONT_EVENT = "frontEventQueue";
......@@ -150,4 +160,9 @@ public class MQQueueConstant {
*/
public static final String DEAD = "rays.dlq";
/**
* 待办事项数量统计
*/
public static final String BACKLOG = "backlogQueue";
}
......@@ -16,10 +16,15 @@ public class MQTopicProducer {
*/
public static final String FILE_TRANSCODE = "topic.fileTranscode";
/**
* 报名新增用户
*/
public static final String BM_ADD_USER = "topic.bmAddUser";
/**
* 音频配音结束(MP3)
*/
public static final String FILE_DUBBING = "topic.fileDubbing";
/**
* 报名新增用户
*/
public static final String BM_ADD_USER = "topic.bmAddUser";
/**
* 应用新增
......@@ -70,8 +75,15 @@ public class MQTopicProducer {
* 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";
......@@ -266,13 +278,28 @@ public class MQTopicProducer {
*/
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 WECHAT_RELATE_INFO = "topic.wechatRelateInfo";
/**
* 更新用户头像
*/
public static final String UPDATE_USER_HEADURL = "topic.updateUserHeadUrl";
}
......@@ -223,6 +223,21 @@ public class ProductTypeConstant {
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};
......@@ -231,7 +246,7 @@ public class ProductTypeConstant {
* 资源型作品(免费即可体验)
*/
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 {
* 应用型作品(伴随应用使用)
*/
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,
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 {
merchant("merchant"), // 商户
channel("channel"), // 渠道
agent("agent"), // 代理
adviser("adviser"); // 顾问
adviser("adviser"), // 顾问
platform("platform"); // 平台
/**
* 值
......
......@@ -48,6 +48,8 @@ public enum WeektaskCode {
UPDATE_BOOK_INFO("update_book_info"),
//调整应用顺序
SET_STEP("set_step"),
//确定回复
DEFINITE_REPLY("definite_reply"),
/**
* -------通用埋点------
*/
......@@ -139,6 +141,15 @@ public enum WeektaskCode {
C_PUBLISH_DYNAMIC("c_publish_dynamic"),
//专题问答设置免费
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 {
*创建抽奖应用
*/
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;
......
......@@ -16,6 +16,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.Configuration;
import org.springframework.context.annotation.Primary;
......@@ -25,139 +26,282 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
@MapperScan(basePackages = DataSourceConfig.PACKAGE,sqlSessionFactoryRef = "sqlSessionFactory")
@ConfigurationProperties(prefix = "spring.datasource")
@MapperScan(basePackages = DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfig {
private Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
static final String PACKAGE = "com.pcloud.common.core.dao";
@Value("${spring.datasource.url}")
private String dbUrl;
@Value("${spring.datasource.type}")
private String dbType;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.initialSize}")
private int initialSize;
@Value("${spring.datasource.minIdle}")
private int minIdle;
@Value("${spring.datasource.maxActive}")
private int maxActive;
@Value("${spring.datasource.maxWait}")
private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
@Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.filters}")
private String filters;
@Value("${spring.datasource.connectionProperties}")
private String connectionProperties;
@Value("${mybatis.mapper-locations}")
private String mapperLocations;
@Value("${mybatis.type-aliases-package}")
private String typeAliasesPackage;
// @Value("${spring.datasource.useGlobalDataSourceStat}")
// private boolean useGlobalDataSourceStat;
//
// @Value("${spring.datasource.druidLoginName}")
// private String druidLoginName;
//
// @Value("${spring.datasource.druidPassword}")
// private String druidPassword;
@Bean(name="druidDataSource")
@Primary //不要漏了这
public DataSource dataSource(){
DruidDataSource datasource = new DruidDataSource();
try {
datasource.setUrl(this.dbUrl);
datasource.setDbType(dbType);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setFilters(filters);
datasource.setConnectionProperties(connectionProperties);
// datasource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);
ArrayList<String> arr = new ArrayList<>();
arr.add("set names utf8mb4;");
datasource.setConnectionInitSqls(arr);
} catch (SQLException e) {
logger.error("druid configuration initialization filter", e);
}
return datasource;
}
@Bean(name = "transactionManager")
public DataSourceTransactionManager transactionManager() {
logger.info("【DataSource】初始化TransactionManager事务管理器,<START>");
return new DataSourceTransactionManager(dataSource());
}
@Bean(name = "sqlSessionFactory")
@Autowired
public SqlSessionFactory sqlSessionFactory(ExecutorInterceptor interceptor) throws Exception {
logger.info("【DataSource】初始化SqlSessionFactory,<START>");
final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
sessionFactoryBean.setVfs(SpringBootVFS.class);
sessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
sessionFactoryBean.setPlugins(new Interceptor[]{interceptor});
return sessionFactoryBean.getObject();
}
@Bean(name = "sqlSessionTemplate")
@Autowired
public SqlSessionTemplate sqlSessionTemplate(ExecutorInterceptor interceptor) throws Exception {
logger.info("【DataSource】初始化SqlSessionTemplate,<START>");
final SqlSessionTemplate sessionFactoryBean = new SqlSessionTemplate(sqlSessionFactory(interceptor));
return sessionFactoryBean;
}
private Logger logger = LoggerFactory.getLogger(DataSourceConfig.class);
static final String PACKAGE = "com.pcloud.common.core.dao";
private String url;
private String type;
private String username;
private String password;
private String driverClassName;
private int initialSize;
private int minIdle;
private int maxActive;
private int maxWait;
private int timeBetweenEvictionRunsMillis;
private int minEvictableIdleTimeMillis;
private String validationQuery;
private boolean testWhileIdle;
private boolean testOnBorrow;
private boolean testOnReturn;
private boolean poolPreparedStatements;
private String filtersNew;
private String connectionPropertiesNew;
@Value("${mybatis.mapper-locations}")
private String mapperLocations;
@Value("${mybatis.type-aliases-package}")
private String typeAliasesPackage;
// @Value("${spring.datasource.useGlobalDataSourceStat}")
// private boolean useGlobalDataSourceStat;
//
// @Value("${spring.datasource.druidLoginName}")
// private String druidLoginName;
//
// @Value("${spring.datasource.druidPassword}")
// private String druidPassword;
@Bean(name = "druidDataSource")
@Primary // 不要漏了这
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
try {
datasource.setUrl(url);
datasource.setDbType(type);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setFilters(filtersNew);
datasource.setConnectionProperties(connectionPropertiesNew);
// datasource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);
ArrayList<String> arr = new ArrayList<>();
arr.add("set names utf8mb4;");
datasource.setConnectionInitSqls(arr);
} catch (SQLException e) {
logger.error("druid configuration initialization filter", e);
}
return datasource;
}
@Bean(name = "transactionManager")
public DataSourceTransactionManager transactionManager() {
logger.info("【DataSource】初始化TransactionManager事务管理器,<START>");
return new DataSourceTransactionManager(dataSource());
}
@Bean(name = "sqlSessionFactory")
@Autowired
public SqlSessionFactory sqlSessionFactory(ExecutorInterceptor interceptor) throws Exception {
logger.info("【DataSource】初始化SqlSessionFactory,<START>");
final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
sessionFactoryBean.setVfs(SpringBootVFS.class);
sessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
sessionFactoryBean.setPlugins(new Interceptor[] { interceptor });
return sessionFactoryBean.getObject();
}
@Bean(name = "sqlSessionTemplate")
@Autowired
public SqlSessionTemplate sqlSessionTemplate(ExecutorInterceptor interceptor) throws Exception {
logger.info("【DataSource】初始化SqlSessionTemplate,<START>");
final SqlSessionTemplate sessionFactoryBean = new SqlSessionTemplate(sqlSessionFactory(interceptor));
return sessionFactoryBean;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
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;
/**
* @描述:
*
* @作者:songx
* @创建时间:2017年2月27日,上午11:23:29 @版本:1.0
*/
public class ConvertQueueDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = 7968821573480010447L;
/**
* 标识
*/
private Long id;
/**
* 文件UUID
*/
private String fileId;
/**
* 来源类型
*/
private String fromType;
/**
* 自定义类型,fromType的二级类型
*/
@ApiModelProperty(name = "自定义类型", dataType = "String")
private String customType;
/**
* 来源标识
*/
private Long fromId;
/**
* 文件路径
*/
private String fileUrl;
/**
* 文件大小
*/
private Long fileSize;
/**
* 文件类型
*/
private String fileType;
/**
* 在缓存中被处理的次数
*/
private int processTimes = 0;
/**
* 转换成功标记,true:成功,false失败
*/
private Boolean state;
/**
* 封面图
*/
private String coverImg;
/**
* 使用地址
*/
private String pilotUrl;
/**
* 视频时长
*/
private Integer duration;
/**
* 视频m3u8地址
*/
private String m3u8Url;
public String getCustomType() {
return customType;
}
public void setCustomType(String customType) {
this.customType = customType;
}
public String getM3u8Url() {
return m3u8Url;
}
public void setM3u8Url(String m3u8Url) {
this.m3u8Url = m3u8Url;
}
public Integer getDuration() {
return duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
public Long getFromId() {
return fromId;
}
public void setFromId(Long fromId) {
this.fromId = fromId;
}
public String getPilotUrl() {
return pilotUrl;
}
public void setPilotUrl(String pilotUrl) {
this.pilotUrl = pilotUrl;
}
public String getCoverImg() {
return coverImg;
}
public void setCoverImg(String coverImg) {
this.coverImg = coverImg;
}
public Boolean getState() {
return state;
}
public void setState(Boolean state) {
this.state = state;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public String getFromType() {
return fromType;
}
public void setFromType(String fromType) {
this.fromType = fromType;
}
/**
* @return Returns the fileUrl.
*/
public String getFileUrl() {
return fileUrl;
}
/**
* @param fileUrl The fileUrl to set.
*/
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
/**
* @return Returns the fileSize.
*/
public Long getFileSize() {
return fileSize;
}
/**
* @param fileSize The fileSize to set.
*/
public void setFileSize(Long fileSize) {
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 + "]";
}
/**
*
*/
private static final long serialVersionUID = 7968821573480010447L;
/**
* 标识
*/
private Long id;
/**
* 文件UUID
*/
private String fileId;
/**
* 来源类型
*/
private String fromType;
/**
* 自定义类型,fromType的二级类型
*/
@ApiModelProperty(name = "自定义类型", dataType = "String")
private String customType;
/**
* 视频截图时间点
*/
private int snapshotTime;
/**
* 来源标识
*/
private Long fromId;
/**
* 文件路径
*/
private String fileUrl;
/**
* 文件大小
*/
private Long fileSize;
/**
* 文件类型
*/
private String fileType;
/**
* 在缓存中被处理的次数
*/
private int processTimes = 0;
/**
* 转换成功标记,true:成功,false失败
*/
private Boolean state;
/**
* 封面图
*/
private String coverImg;
/**
* 使用地址
*/
private String pilotUrl;
/**
* 视频时长
*/
private Integer duration;
/**
* 视频m3u8地址
*/
private String m3u8Url;
public int getSnapshotTime() {
return snapshotTime;
}
public void setSnapshotTime(int snapshotTime) {
this.snapshotTime = snapshotTime;
}
public String getCustomType() {
return customType;
}
public void setCustomType(String customType) {
this.customType = customType;
}
public String getM3u8Url() {
return m3u8Url;
}
public void setM3u8Url(String m3u8Url) {
this.m3u8Url = m3u8Url;
}
public Integer getDuration() {
return duration;
}
public void setDuration(Integer duration) {
this.duration = duration;
}
public Long getFromId() {
return fromId;
}
public void setFromId(Long fromId) {
this.fromId = fromId;
}
public String getPilotUrl() {
return pilotUrl;
}
public void setPilotUrl(String pilotUrl) {
this.pilotUrl = pilotUrl;
}
public String getCoverImg() {
return coverImg;
}
public void setCoverImg(String coverImg) {
this.coverImg = coverImg;
}
public Boolean getState() {
return state;
}
public void setState(Boolean state) {
this.state = state;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public String getFromType() {
return fromType;
}
public void setFromType(String fromType) {
this.fromType = fromType;
}
/**
* @return Returns the fileUrl.
*/
public String getFileUrl() {
return fileUrl;
}
/**
* @param fileUrl
* The fileUrl to set.
*/
public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;
}
/**
* @return Returns the fileSize.
*/
public Long getFileSize() {
return fileSize;
}
/**
* @param fileSize
* The fileSize to set.
*/
public void setFileSize(Long fileSize) {
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{
* 模板参数
*/
private Map<String, Object> paramKeyMap;
/**
* 设备类型
*/
private String deviceType;
/**
* 应用id
*/
private Long appId;
public String getRegistrationId() {
return registrationId;
......@@ -64,12 +72,35 @@ public class SendAppMessageDto implements Serializable{
public void setIsNow(Boolean 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
public String toString() {
return "SendAppMessageDto [registrationId=" + registrationId + ", adviserId=" + adviserId + ", typeCode="
+ typeCode + ", isNow=" + isNow + ", paramKeyMap=" + paramKeyMap + "]";
return "SendAppMessageDto{" +
"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 {
/**
* 直播
*/
LIVE_HOMEWORD("LIVE_HOMEWORD");
LIVE_HOMEWORD("LIVE_HOMEWORD"),
/**
* 音频
*/
AUDIOAPP_PDF("AUDIOAPP_PDF"),
/**
* 文件管理中心
*/
CONVERT_PDF("CONVERT_PDF");
/**
* 值
......
......@@ -9,7 +9,10 @@ import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
......@@ -22,6 +25,8 @@ import com.pcloud.common.permission.PermissionException;
import feign.FeignException;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import java.util.List;
/**
*
* @描述:异常集中处理
......@@ -92,6 +97,23 @@ public class GlobalExceptionHandler {
LOGGER.warn("【响应未结束】" + exception.getMessage(), exception);
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) {
LOGGER.info("【业务异常】" + exception.getMessage(), exception);
......
......@@ -178,6 +178,10 @@
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
......@@ -291,13 +295,6 @@
<artifactId>aliyun-java-sdk-mts</artifactId>
</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 -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
......@@ -387,6 +384,12 @@
<version>2.0</version>
</dependency>
<!-- util sdk -->
<dependency>
<groupId>com.dcg.sdk</groupId>
<artifactId>util-sdk</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</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 {
WISH("WISH"),// 愿望单
LIVEAPP("LIVEAPP"), //直播3.0
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;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.pcloud.common.constant.AliyunConstant;
import com.pcloud.common.constant.FilePathConst;
import com.pcloud.common.constant.OSConstant;
import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException;
import com.pcloud.common.utils.aliyun.OssUtils;
import com.pcloud.common.utils.encode.CpdetectorEncoding;
import com.pcloud.common.utils.string.StringTools;
import com.pcloud.common.utils.string.StringUtil;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;
/**
* @描述:文件工具类. @作者:DiSeng.H
* @创建时间:2016年3月10日,上午11:56:26 @版本:1.0
*/
public class FileUtils {
/**
* logger
*/
private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
/**
* PDF
*/
public final static String PDF = "PDF";
/**
* XML
*/
public final static String XML = "XML";
/**
* IMAGE
*/
public final static String IMAGE = "IMAGE";
/**
* 音频
*/
public final static String AUDIO = "AUDIO";
/**
* 视频格式
*/
public final static String VIDEO = "VIDEO";
/**
* 压缩格式
*/
public final static String COMPRESS = "COMPRESS";
/**
* 办公软件
*/
public final static String EDITOR = "EDITOR";
/**
* 文本格式
*/
public final static String TEXT = "TEXT";
/**
* PDF文件格式
*/
public static final String[] PDF_GATHER = {"PDF"};
/**
* XML文件格式
*/
public static final String[] XML_GATHER = {"XML"};
/**
* 图片文件格式
*/
public static final String[] IMAGE_GATHER = {"BMP", "JPG", "GIF", "PNG", "PCX", "TIF", "JPEG", "SVG"};
/**
* 音頻文件格式 【"LRC" 为歌词字幕(这里作为音頻文件上传)】
*/
public static final String[] AUDIO_GATHER = {"AMR", "MP3", "WMA", "WAV", "AAC", "APE", "M4A"};
/**
* 視頻文件格式 【"SRT", "SSA", "SMI", "SUB" 为视频“外挂型”字幕(这里作为视频文件上传)】
*/
public static final String[] VIDEO_GATHER = {"MPG", "MPEG", "AVI", "MOV", "ASF", "WMV", "NAVI", "3GP", "MKV",
"FLV", "F4V", "RMVB", "RM", "MP4", "SRT", "SSA", "SMI", "SUB", "ASX", "M3U8"};
/**
* 压缩包文件格式
*/
public static final String[] COMPRESS_GATHER = {"RAR", "ZIP"};
/**
* 文件格式
*/
public static final String[] TEXT_GATHER = {"TXT", "LRC"};
/**
* 编辑器格式
*/
public static final String[] EDITOR_GATHER = {"DOC", "DOCX", "XLS", "XLSX", "PPT", "PPTX"};
/**
* word格式
*/
public static final String[] WORD_GATHER = {"DOC", "DOCX"};
/**
* excel格式
*/
public static final String[] EXCEL_GATHER = {"XLS", "XLSX", "XLSM", "XLT", "XLTX", "XLTM", "CSV"};
/**
* PPT格式
*/
public static final String[] PPT_GATHER = {"PPT", "PPTX"};
/**
* 根据文件类型获取文件分类
*
* @param fileType
* @return
*/
public static String getGatherName(String fileType) {
if (StringUtil.isEmpty(fileType)) {
return null;
}
// IMAGE
if (Arrays.asList(IMAGE_GATHER).contains(fileType.toUpperCase())) {
return IMAGE;
}
// AUDIO
if (Arrays.asList(AUDIO_GATHER).contains(fileType.toUpperCase())) {
return AUDIO;
}
// VIDEO
if (Arrays.asList(VIDEO_GATHER).contains(fileType.toUpperCase())) {
return VIDEO;
}
// PDF
if (Arrays.asList(PDF_GATHER).contains(fileType.toUpperCase())) {
return PDF;
}
// XML
if (Arrays.asList(XML_GATHER).contains(fileType.toUpperCase())) {
return XML;
}
// COMPRESS
if (Arrays.asList(COMPRESS_GATHER).contains(fileType.toUpperCase())) {
return COMPRESS;
}
// EDITOR
if (Arrays.asList(EDITOR_GATHER).contains(fileType.toUpperCase())) {
return EDITOR;
}
// COMPRESS
if (Arrays.asList(TEXT_GATHER).contains(fileType.toUpperCase())) {
return TEXT;
}
return null;
}
/**
* 传入文件夹路径,该方法能够实现创建整个路径
*
* @param path 文件夹路径,不包含文件名称及后缀名
*/
public static boolean isDir(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return false;
}
String[] paths = filePath.split("/");
String temp = "";
for (int i = 0; i < paths.length; i++) {
if (i == 0) {
temp = paths[0];
} else {
temp += "/" + paths[i];
}
creatDir(temp);
}
return true;
}
/**
* 该方法用来判断文件是否存在,如果不存在则创建
*
* @param filePath
*/
public static boolean creatFile(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return false;
}
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
return true;
} catch (Exception e) {
LOGGER.error("【文件工具】创建文件失败,<ERROR>:" + e.getMessage(), e);
}
}
return false;
}
/**
* 该方法用来判断文件是否存在,如果不存在则创建,该方法能够实现创建整个路径
*
* @param filePath
*/
public static boolean creatFiles(String filePath) {
LOGGER.info("【文件API】创建文件,同时创建整个路径.<START>.[filePath]=" + filePath);
if (StringUtil.isEmpty(filePath)) {
return false;
}
filePath = filePath.replace(File.separator, "/");
String dirPath = filePath.substring(0, filePath.lastIndexOf("/"));
File dirFile = new File(dirPath);
if (!dirFile.exists()) {
try {
dirFile.mkdirs();
} catch (Exception e) {
LOGGER.error("【文件工具】创建文件夹失败,<ERROR>:" + e.getMessage(), e);
return false;
}
}
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
return true;
} catch (Exception e) {
LOGGER.error("【文件工具】创建文件失败,<ERROR>:" + e.getMessage(), e);
}
}
LOGGER.info("【文件API】创建文件,同时创建整个路径.<END>");
return false;
}
/**
* 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做
*
* @param filePath
*/
public static boolean creatDir(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return false;
}
File file = new File(filePath);
if (!file.exists()) {
file.mkdir();
return true;
}
return false;
}
/**
* 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做 该方法能够实现创建整个路径
*
* @param filePath
*/
public static boolean creatDirs(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return false;
}
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
return true;
}
return false;
}
/**
* 获取文件类型
*
* @param filePath
*/
public static String getFileType(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return null;
}
int index1 = filePath.lastIndexOf(".");
if (index1 < 1) {
return null;
}
int index2 = filePath.lastIndexOf("?");
if (index2 > index1) {
filePath = filePath.substring(0, filePath.lastIndexOf("?"));
}
filePath = filePath.replace("/", OSConstant.SEPARATOR);
int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR);
if (index3 > index1) {
return null;
}
return filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()).toLowerCase();
}
/**
* 获取文件名称
*
* @param filePath
*/
public static String getFileName(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return null;
}
String fileName = null;
filePath = filePath.replace("/", OSConstant.SEPARATOR);
int index1 = filePath.lastIndexOf(".");
if (index1 > -1) {
int index2 = filePath.lastIndexOf("?");
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);
} else {
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1,
filePath.lastIndexOf("."));
}
} else {
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1);
}
return formatName(fileName);
}
/**
* 获取文件名称包括后缀
*
* @param filePath
* @return
*/
public static String getFileNameAll(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return null;
}
String fileName = getFileName(filePath);
if (StringUtil.isEmpty(fileName)) {
return null;
}
String fileType = getFileType(filePath);
return StringUtil.isEmpty(fileType) ? fileName : fileName + "." + fileType;
}
/**
* 格式化文件名称,过滤特殊字符(名称太长进行截断)
*
* @param fileName
*/
public static String formatName(String fileName) {
if (StringUtil.isEmpty(fileName)) {
return null;
}
try {
String regEx = "[*/\\\\:?\"<|>\\s+%#&=.()]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(fileName);
String result = m.replaceAll("").trim();
// 文件名称过长的话,限制40个字
return result.length() > 40 ? result.substring(0, 40) : result;
} catch (Exception e) {
LOGGER.error("【文件API】格式化文件名称.[formatName]:" + e.getMessage(), e);
return UUIDUitl.taskName();
}
}
/**
* 获取文件所在的目录
*
* @param filePath
* @return
*/
public static String getFileFolder(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return null;
}
return filePath.substring(0, filePath.lastIndexOf(OSConstant.SEPARATOR));
}
/**
* 获取http文件路径的域名
*
* @param fileUrl
* @return
*/
public static String getDomainName(String fileUrl) {
if (StringUtil.isEmpty(fileUrl)) {
return null;
}
Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
Matcher m = p.matcher(fileUrl);
if (m.find()) {
return m.group();
}
return null;
}
/**
* FileUtils工具 File @throws
*/
public static File copyURLToFile(String url, String dir) throws Exception {
try {
URL httpurl = new URL(url);
File f = new File(dir);
org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f);
return f;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 根据路径删除指定的目录或文件,无论存在与否
*
* @param sPath 要删除的目录或文件
* @return 删除成功返回 true,否则返回 false。
*/
public static boolean deleteFolder(String sPath) {
if (StringUtil.isEmpty(sPath)) {
return false;
}
boolean flag = false;
File file = new File(sPath);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
return deleteFile(sPath);
} else { // 为目录时调用删除目录方法
return deleteDirectory(sPath);
}
}
}
/**
* 删除单个文件
*
* @param sPath 被删除文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String sPath) {
if (StringUtil.isEmpty(sPath)) {
return false;
}
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
/**
* 删除目录(文件夹)以及目录下的文件
*
* @param sPath 被删除目录的文件路径
* @return 目录删除成功返回true,否则返回false
*/
public static boolean deleteDirectory(String sPath) {
if (StringUtil.isEmpty(sPath)) {
return false;
}
// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
File dirFile = new File(sPath);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
boolean flag = true;
// 删除文件夹下的所有文件(包括子目录)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
} // 删除子目录
else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag)
break;
}
}
if (!flag)
return false;
// 删除当前目录
if (dirFile.delete()) {
return true;
} else {
return false;
}
}
/**
* 检查文件是否存在
*
* @param filePath
* @return
*/
public static boolean checkFile(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return false;
}
File file = new File(filePath);
if (!file.isFile()) {
return false;
}
return true;
}
/**
* | FileUtils工具
*/
public static void downloadFileFromUrl(String url, String localFilePath) throws FileException {
LOGGER.info("【文件API】下载文件[本地文件].<START>.[url]=" + url + ",[localFilePath]=" + localFilePath);
creatFiles(localFilePath);
try {
if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) {
OssUtils.downloadFile(url, localFilePath);
// } else if (url.contains("/group")) {
// Map<String, String> paramMap = FdfsUtils.splitFilePath(url);
// FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value),
// paramMap.get(FdfsEnum.FILE_ID.value), localFilePath);
} else {
File f = new File(localFilePath);
URL httpurl = new URL(url);
org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f);
}
} catch (Exception e) {
LOGGER.error("【文件API】下载文件.[copyURLToFile]:" + e.getMessage(), e);
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
}
}
/**
* IOUtils工具
*/
public static byte[] downloadByteFromUrl(String url) throws FileException {
LOGGER.info("【文件API】下载文件[byte].<START>.[url]=" + url);
if (StringUtil.isEmpty(url)) {
return null;
}
byte[] data = null;
try {
if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) {
data = OssUtils.downloadFile2Byte(url);
// } else if (url.contains("/group")) {
// Map<String, String> paramMap = FdfsUtils.splitFilePath(url);
// data =
// FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value),
// paramMap.get(FdfsEnum.FILE_ID.value));
} else {
URL httpurl = new URL(url);
data = IOUtils.toByteArray(httpurl);
}
} catch (Exception e) {
LOGGER.error("【文件API】下载文件.[toByteArray]:" + e.getMessage(), e);
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
}
return data;
}
/**
* InputStream
*/
@Deprecated
public static InputStream downloadStreamFromUrl(String url) throws FileException {
try {
URL httpurl = new URL(url);
return httpurl.openStream();
} catch (Exception e) {
LOGGER.error("【文件API】下载文件.[openStream]:" + e.getMessage(), e);
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
}
}
/**
* 普通情况下保存字节数据到本地文件
*/
public synchronized static boolean saveBytesTofile(File file, byte[] data) throws BizException {
FileOutputStream fos = null;
// 建立输出字节流
try {
fos = new FileOutputStream(file);
fos.write(data); // 用FileOutputStream 的write方法写入字节数组
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 复制一个文件到另一个目录下
*
* @throws BizException
*/
public static void copyFileToFolder(File inputFile, File outputFile) throws BizException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(inputFile);
fos = new FileOutputStream(outputFile);
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) {
ioe.printStackTrace();
}
}
/**
* 合并两个文件
*
* @param outFile 目标文件
* @param leafFile 源文件
*/
public static void mergeFiles(File outFile, File leafFile) {
FileOutputStream fos = null;
FileInputStream fis = null;
if (!outFile.exists()) {
try {
outFile.createNewFile();
} catch (Exception e) {
throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败");
}
}
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);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
if (fos != null)
fos.close();
} catch (Exception e) {
}
}
}
/**
* 合并多个文件
*
* @param outFile 输出文件,
* @param leafFiles 文件碎片集
*/
public static void mergeFileList(File outFile, List<File> leafFiles) {
FileOutputStream fos = null;
FileInputStream fis = null;
if (!outFile.exists()) {
try {
outFile.createNewFile();
} catch (Exception e) {
throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败");
}
}
try {
// 合并其实就是文件的续写,写成true
fos = new FileOutputStream(outFile, true);
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);
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
if (fos != null)
fos.close();
} catch (Exception e) {
}
}
}
/**
* 音频文件转换
*
* @param data 音频byte数组
* @param sourExt 原始后缀
* @param ext 新后缀
* @return
* @author PENG
*/
public static String audioFormatConvert(byte[] data, String sourExt, String ext) {
File tmpdir = new File("tempdir/local");
if (!tmpdir.exists()) {
try {
tmpdir.mkdirs();
} catch (SecurityException ex) {
System.out.println("无法创建临时文件夹");
ex.printStackTrace();
}
}
String name = UUID.randomUUID().toString();
File source = new File(tmpdir, name + "." + sourExt);
boolean creat = saveBytesTofile(source, data);
if (creat) {
File target = new File(tmpdir, name + "." + ext);
AudioAttributes audio = new AudioAttributes();
Encoder encoder = new Encoder();
audio.setCodec("libmp3lame");
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat(ext.toLowerCase());
attrs.setAudioAttributes(audio);
try {
encoder.encode(source, target, attrs);
return target.getPath();
} catch (IllegalArgumentException e) {
e.printStackTrace();
return null;
} catch (InputFormatException e) {
e.printStackTrace();
return null;
} catch (EncoderException e) {
e.printStackTrace();
return target.getPath();
}
} else {
return null;
}
}
/**
* 获取文本的内容
*
* @param url
* @return
*/
public static String getTextString(String url) {
LOGGER.info("【文件API】获取文本的内容.<START>.[url]=" + url);
if (StringUtil.isEmpty(url)) {
return null;
}
StringBuilder lrcString = new StringBuilder();
InputStream is = 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");
} else {
Object charSet = CpdetectorEncoding.getEncoding(bt, false);
if (charSet.toString().equals("UTF-8")) {
isr = new InputStreamReader(is, "UTF-8");
} else {
isr = new InputStreamReader(new ByteArrayInputStream(bt), "GBK");
}
}
BufferedReader br = new BufferedReader(isr);// 构造一个BufferedReader类来读取文件
String s;
while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行
lrcString.append(System.lineSeparator() + s);
}
} catch (Exception e) {
LOGGER.error("【文件工具】读取文件内容.<ERROR>:" + e.getMessage(), e);
} finally {
try {
if (isr != null)
isr.close();
if (is != null)
is.close();
} catch (Exception e2) {
}
}
LOGGER.info("【文件API】获取文本的内容.<END>");
return lrcString.toString();
}
/**
* java 8 读取文本内容
*
* @param url
* @return
*/
public static String getTextString8(String url) {
LOGGER.info("【文件API】获取文本的内容8.<START>.[url]=" + url);
StringBuilder result = new StringBuilder();
String fileType = getFileType(url);
String localFilePath = url;
if (url.startsWith("http")) {
localFilePath = FilePathConst.TEXT_PATH + UUIDUitl.taskName() + "." + fileType;
downloadFileFromUrl(url, localFilePath);
}
try {
Stream<String> lines = Files.lines(Paths.get(localFilePath), StandardCharsets.UTF_8);
lines.forEach(line -> {
result.append(line + System.lineSeparator());
});
} catch (Exception e) {
LOGGER.error("【文件工具】读取文件内容8.<ERROR>:" + e.getMessage(), e);
} finally {
deleteFile(localFilePath);
}
LOGGER.info("【文件API】获取文本的内容8.<END>");
return result.toString();
}
/**
* 文件剪切,网络路径、按文件大小的百分比
*
* @param url
* @param percent 1~100的整数
* @return 返回剪切后上传后的文件路径
* @throws BizException
*/
public static String clipByPercent(String url, int percent) throws BizException {
LOGGER.info("【文件API】文件剪切,按百分比.<START>.[url]=" + url);
if (StringUtil.isEmpty(url)) {
return null;
}
String fileType = FileUtils.getFileType(url);
if (!FileUtils.VIDEO.equals(FileUtils.getGatherName(fileType))) {
return null;
}
// 下载文件
String downloadPath = FilePathConst.DOWNLOAD_PATH + UUIDUitl.generateString(32) + "." + fileType;
FileUtils.downloadFileFromUrl(url, downloadPath);
// 剪切文件
String cutPath = clipByPercent(new File(downloadPath), percent);
// 重新上传文件
UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile(cutPath, null);
// 删除本地文件
FileUtils.deleteFile(downloadPath);
FileUtils.deleteFile(cutPath);
LOGGER.info("【文件API】文件剪切,按百分比.<END>.[uploadResultInfo]=" + uploadResultInfo);
return uploadResultInfo == null ? null : uploadResultInfo.getUrl();
}
/**
* 文件剪切,本地路径、按百分比
*
* @param inputFile
* @param cutPercent 1~100的整数
* @return 返回本地路径地址
* @throws BizException
*/
public static String clipByPercent(File inputFile, int cutPercent) throws BizException {
LOGGER.info("【文件API】文件剪切.<START>.[cutPercent]=" + cutPercent);
if (inputFile == null || inputFile.length() <= 0) {
throw new FileException(FileException.FILE_NOT_EXIST, "不是有效的文件");
}
if (cutPercent > 100 || cutPercent < 1) {
throw new FileException(FileException.FILE_READ_FAILURE, "百分比必须是1~100之间的整数");
}
return clipByLength(inputFile, Math.round(inputFile.length() * cutPercent / 100.0d));
}
/**
* 文件剪切
*
* @param inputFile 待剪切的文件
* @param cutLength 剪切长度(Byte)
*/
public static String clipByLength(File inputFile, long cutLength) throws BizException {
LOGGER.info("【文件API】文件剪切.<START>.[cutLength]=" + cutLength);
if (inputFile == null || inputFile.length() <= 0) {
throw new FileException(FileException.FILE_NOT_EXIST, "不是有效的文件");
}
if (cutLength < 1024) {
throw new FileException(FileException.FILE_READ_FAILURE, "剪切的文件必须大于1KB");
}
// 输出文件路径
String outFilePath = FilePathConst.CUT_PATH + UUIDUitl.generateString(12) + "_" + inputFile.getName();
creatFiles(outFilePath);
// 剪切长度
cutLength = cutLength > inputFile.length() ? inputFile.length() : cutLength;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
// 两个输入流
bis = new BufferedInputStream(new FileInputStream(inputFile));
// 缓冲字节输出流
bos = new BufferedOutputStream(new FileOutputStream(outFilePath));
// 读取多少次
long index = cutLength % 1024 > 0 ? cutLength / 1024 + 1 : cutLength / 1024;
int mod = (int) cutLength % 1024;
byte[] bt = new byte[1024];
int len = 0;
for (int i = 0; i < index; i++) {
if (i + 1 == index && mod != 0) {
bt = new byte[mod];
len = bis.read(bt);
} else {
len = bis.read(bt);
}
if (len != -1) {
bos.write(bt, 0, len);
}
}
bos.flush();
} catch (IOException e) {
LOGGER.error("【文件工具】剪切文件内容:" + e.getMessage(), e);
throw new FileException(FileException.FILE_READ_FAILURE, "文件剪切失败");
} finally {
try {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
} catch (IOException e) {
LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e);
}
}
LOGGER.info("【文件API】文件剪切.<END>");
return outFilePath;
}
/**
* 将文件转成base64 字符串
*
* @param data
* @return *
* @throws Exception
*/
public static String encodeBase64File(byte[] data) throws BizException {
try {
return new String(Base64.encodeBase64(data));
} catch (Exception e) {
LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e);
return null;
}
}
/**
* 将base64字符解码保存文件
*
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static boolean decoderBase64File(String base64Code, String targetPath) throws BizException {
if (base64Code == null)
return false;
OutputStream out = null;
try {
// Base64解码
byte[] b = Base64.decodeBase64(targetPath);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成jpeg图片
out = new FileOutputStream(targetPath);
out.write(b);
out.flush();
} catch (Exception e) {
LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e);
return false;
} finally {
try {
if (out != null)
out.close();
} catch (Exception e) {
}
}
return true;
}
/**
* 本地文件到byte数组
*
* @param path
* @return
*/
public static byte[] file2byte(String path) {
byte[] data = null;
FileInputStream fis = null;
ByteArrayOutputStream os = null;
try {
fis = new FileInputStream(new File(path));
os = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = fis.read(buf)) != -1) {
os.write(buf, 0, numBytesRead);
}
data = os.toByteArray();
} catch (Exception e) {
LOGGER.error("【文件工具】文件到byte数组:" + e.getMessage(), e);
} finally {
try {
if (fis != null)
fis.close();
if (os != null)
os.close();
} catch (IOException e) {
LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e);
}
}
return data;
}
/**
* 从输入流中获取数据
*
* @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();
}
}
package com.pcloud.common.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.pcloud.common.constant.AliyunConstant;
import com.pcloud.common.constant.FilePathConst;
import com.pcloud.common.constant.OSConstant;
import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException;
import com.pcloud.common.utils.aliyun.OssUtils;
import com.pcloud.common.utils.encode.CpdetectorEncoding;
import com.pcloud.common.utils.string.StringTools;
import com.pcloud.common.utils.string.StringUtil;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;
/**
* @描述:文件工具类. @作者:DiSeng.H
* @创建时间:2016年3月10日,上午11:56:26 @版本:1.0
*/
public class FileUtils {
/**
* logger
*/
private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
/**
* PDF
*/
public final static String PDF = "PDF";
/**
* XML
*/
public final static String XML = "XML";
/**
* IMAGE
*/
public final static String IMAGE = "IMAGE";
/**
* 音频
*/
public final static String AUDIO = "AUDIO";
/**
* 视频格式
*/
public final static String VIDEO = "VIDEO";
/**
* 压缩格式
*/
public final static String COMPRESS = "COMPRESS";
/**
* 办公软件
*/
public final static String EDITOR = "EDITOR";
/**
* 文本格式
*/
public final static String TEXT = "TEXT";
/**
* OFFICE
*/
public final static String OFFICE = "OFFICE";
/**
* PDF文件格式
*/
public static final String[] PDF_GATHER = { "PDF" };
/**
* XML文件格式
*/
public static final String[] XML_GATHER = { "XML" };
/**
* 图片文件格式
*/
public static final String[] IMAGE_GATHER = { "BMP", "JPG", "GIF", "PNG", "PCX", "TIF", "JPEG", "SVG", "WEBP" };
/**
* 音頻文件格式 【"LRC" 为歌词字幕(这里作为音頻文件上传)】
*/
public static final String[] AUDIO_GATHER = { "AMR", "MP3", "WMA", "WAV", "AAC", "APE", "M4A" };
/**
* 視頻文件格式 【"SRT", "SSA", "SMI", "SUB" 为视频“外挂型”字幕(这里作为视频文件上传)】
*/
public static final String[] VIDEO_GATHER = { "MPG", "MPEG", "AVI", "MOV", "ASF", "WMV", "NAVI", "3GP", "MKV",
"FLV", "F4V", "RMVB", "RM", "MP4", "SRT", "SSA", "SMI", "SUB", "ASX", "M3U8" };
/**
* 压缩包文件格式
*/
public static final String[] COMPRESS_GATHER = { "RAR", "ZIP" };
/**
* 文件格式
*/
public static final String[] TEXT_GATHER = { "TXT", "LRC" };
/**
* 编辑器格式
*/
public static final String[] EDITOR_GATHER = { "DOC", "DOCX", "XLS", "XLSX", "PPT", "PPTX" };
/**
* word格式
*/
public static final String[] WORD_GATHER = { "DOC", "DOCX" };
/**
* excel格式
*/
public static final String[] EXCEL_GATHER = { "XLS", "XLSX", "XLSM", "XLT", "XLTX", "XLTM", "CSV" };
/**
* PPT格式
*/
public static final String[] PPT_GATHER = { "PPT", "PPTX" };
/**
* office
*/
public static final String[] OFFICE_GATHER = { "DOC", "DOCX", "PPT", "PPTX", "XLS", "XLSX", "XLSM", "XLT", "XLTX",
"XLTM", "CSV" };
/**
* 根据文件类型获取文件分类
*
* @param fileType
* @return
*/
public static String getGatherName(String fileType) {
if (StringUtil.isEmpty(fileType)) {
return null;
}
// IMAGE
if (Arrays.asList(IMAGE_GATHER).contains(fileType.toUpperCase())) {
return IMAGE;
}
// AUDIO
if (Arrays.asList(AUDIO_GATHER).contains(fileType.toUpperCase())) {
return AUDIO;
}
// VIDEO
if (Arrays.asList(VIDEO_GATHER).contains(fileType.toUpperCase())) {
return VIDEO;
}
// PDF
if (Arrays.asList(PDF_GATHER).contains(fileType.toUpperCase())) {
return PDF;
}
// XML
if (Arrays.asList(XML_GATHER).contains(fileType.toUpperCase())) {
return XML;
}
// COMPRESS
if (Arrays.asList(COMPRESS_GATHER).contains(fileType.toUpperCase())) {
return COMPRESS;
}
// EDITOR
if (Arrays.asList(EDITOR_GATHER).contains(fileType.toUpperCase())) {
return EDITOR;
}
// TEXT
if (Arrays.asList(TEXT_GATHER).contains(fileType.toUpperCase())) {
return TEXT;
}
// OFFICE
if (Arrays.asList(OFFICE_GATHER).contains(fileType.toUpperCase())) {
return OFFICE;
}
return null;
}
/**
* 传入文件夹路径,该方法能够实现创建整个路径
*
* @param path
* 文件夹路径,不包含文件名称及后缀名
*/
public static boolean isDir(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return false;
}
String[] paths = filePath.split("/");
String temp = "";
for (int i = 0; i < paths.length; i++) {
if (i == 0) {
temp = paths[0];
} else {
temp += "/" + paths[i];
}
creatDir(temp);
}
return true;
}
/**
* 该方法用来判断文件是否存在,如果不存在则创建
*
* @param filePath
*/
public static boolean creatFile(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return false;
}
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
return true;
} catch (Exception e) {
LOGGER.error("【文件工具】创建文件失败,<ERROR>:" + e.getMessage(), e);
}
}
return false;
}
/**
* 该方法用来判断文件是否存在,如果不存在则创建,该方法能够实现创建整个路径
*
* @param filePath
*/
public static boolean creatFiles(String filePath) {
LOGGER.info("【文件API】创建文件,同时创建整个路径.<START>.[filePath]=" + filePath);
if (StringUtil.isEmpty(filePath)) {
return false;
}
filePath = filePath.replace(File.separator, "/");
String dirPath = filePath.substring(0, filePath.lastIndexOf("/"));
File dirFile = new File(dirPath);
if (!dirFile.exists()) {
try {
dirFile.mkdirs();
} catch (Exception e) {
LOGGER.error("【文件工具】创建文件夹失败,<ERROR>:" + e.getMessage(), e);
return false;
}
}
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
return true;
} catch (Exception e) {
LOGGER.error("【文件工具】创建文件失败,<ERROR>:" + e.getMessage(), e);
}
}
LOGGER.info("【文件API】创建文件,同时创建整个路径.<END>");
return false;
}
/**
* 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做
*
* @param filePath
*/
public static boolean creatDir(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return false;
}
File file = new File(filePath);
if (!file.exists()) {
file.mkdir();
return true;
}
return false;
}
/**
* 该方法用来判断文件夹是否存在,如果不存在则创建,存在则什么都不做 该方法能够实现创建整个路径
*
* @param filePath
*/
public static boolean creatDirs(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return false;
}
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
return true;
}
return false;
}
/**
* 获取文件类型
*
* @param filePath
*/
public static String getFileType(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return null;
}
int index1 = filePath.lastIndexOf(".");
if (index1 < 1) {
return null;
}
int index2 = filePath.lastIndexOf("?");
if (index2 > index1) {
filePath = filePath.substring(0, filePath.lastIndexOf("?"));
}
filePath = filePath.replace("/", OSConstant.SEPARATOR);
int index3 = filePath.lastIndexOf(OSConstant.SEPARATOR);
if (index3 > index1) {
return null;
}
return filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length()).toLowerCase();
}
/**
* 获取文件名称
*
* @param filePath
*/
public static String getFileName(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return null;
}
String fileName = null;
filePath = filePath.replace("/", OSConstant.SEPARATOR);
int index1 = filePath.lastIndexOf(".");
if (index1 > -1) {
int index2 = filePath.lastIndexOf("?");
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);
} else {
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1,
filePath.lastIndexOf("."));
}
} else {
fileName = filePath.substring(filePath.lastIndexOf(OSConstant.SEPARATOR) + 1);
}
return formatName(fileName);
}
/**
* 获取文件名称包括后缀
*
* @param filePath
* @return
*/
public static String getFileNameAll(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return null;
}
String fileName = getFileName(filePath);
if (StringUtil.isEmpty(fileName)) {
return null;
}
String fileType = getFileType(filePath);
return StringUtil.isEmpty(fileType) ? fileName : fileName + "." + fileType;
}
/**
* 格式化文件名称,过滤特殊字符(名称太长进行截断)
*
* @param fileName
*/
public static String formatName(String fileName) {
if (StringUtil.isEmpty(fileName)) {
return null;
}
try {
String regEx = "[*/\\\\:?\"<|>\\s+%#&=.()]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(fileName);
String result = m.replaceAll("").trim();
// 文件名称过长的话,限制40个字
return result.length() > 40 ? result.substring(0, 40) : result;
} catch (Exception e) {
LOGGER.error("【文件API】格式化文件名称.[formatName]:" + e.getMessage(), e);
return UUIDUitl.taskName();
}
}
/**
* 获取文件所在的目录
*
* @param filePath
* @return
*/
public static String getFileFolder(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return null;
}
return filePath.substring(0, filePath.lastIndexOf(OSConstant.SEPARATOR));
}
/**
* 获取http文件路径的域名
*
* @param fileUrl
* @return
*/
public static String getDomainName(String fileUrl) {
if (StringUtil.isEmpty(fileUrl)) {
return null;
}
Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
Matcher m = p.matcher(fileUrl);
if (m.find()) {
return m.group();
}
return null;
}
/**
* FileUtils工具 File @throws
*/
public static File copyURLToFile(String url, String dir) throws Exception {
try {
URL httpurl = new URL(url);
File f = new File(dir);
org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f);
return f;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 根据路径删除指定的目录或文件,无论存在与否
*
* @param sPath 要删除的目录或文件
* @return 删除成功返回 true,否则返回 false。
*/
public static boolean deleteFolder(String sPath) {
if (StringUtil.isEmpty(sPath)) {
return false;
}
boolean flag = false;
File file = new File(sPath);
// 判断目录或文件是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判断是否为文件
if (file.isFile()) { // 为文件时调用删除文件方法
return deleteFile(sPath);
} else { // 为目录时调用删除目录方法
return deleteDirectory(sPath);
}
}
}
/**
* 删除单个文件
*
* @param sPath 被删除文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String sPath) {
if (StringUtil.isEmpty(sPath)) {
return false;
}
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
/**
* 删除目录(文件夹)以及目录下的文件
*
* @param sPath 被删除目录的文件路径
* @return 目录删除成功返回true,否则返回false
*/
public static boolean deleteDirectory(String sPath) {
if (StringUtil.isEmpty(sPath)) {
return false;
}
// 如果sPath不以文件分隔符结尾,自动添加文件分隔符
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
File dirFile = new File(sPath);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
boolean flag = true;
// 删除文件夹下的所有文件(包括子目录)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
} // 删除子目录
else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag)
break;
}
}
if (!flag)
return false;
// 删除当前目录
if (dirFile.delete()) {
return true;
} else {
return false;
}
}
/**
* 检查文件是否存在
*
* @param filePath
* @return
*/
public static boolean checkFile(String filePath) {
if (StringUtil.isEmpty(filePath)) {
return false;
}
File file = new File(filePath);
if (!file.isFile()) {
return false;
}
return true;
}
/**
* | FileUtils工具
*/
public static void downloadFileFromUrl(String url, String localFilePath) throws FileException {
LOGGER.info("【文件API】下载文件[本地文件].<START>.[url]=" + url + ",[localFilePath]=" + localFilePath);
creatFiles(localFilePath);
try {
if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) {
OssUtils.downloadFile(url, localFilePath);
// } else if (url.contains("/group")) {
// Map<String, String> paramMap = FdfsUtils.splitFilePath(url);
// FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value),
// paramMap.get(FdfsEnum.FILE_ID.value), localFilePath);
} else {
File f = new File(localFilePath);
URL httpurl = new URL(url);
org.apache.commons.io.FileUtils.copyURLToFile(httpurl, f);
}
} catch (Exception e) {
LOGGER.error("【文件API】下载文件.[copyURLToFile]:" + e.getMessage(), e);
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
}
}
/**
* IOUtils工具
*/
public static byte[] downloadByteFromUrl(String url) throws FileException {
LOGGER.info("【文件API】下载文件[byte].<START>.[url]=" + url);
if (StringUtil.isEmpty(url)) {
return null;
}
byte[] data = null;
try {
if (StringTools.contains(url, AliyunConstant.OSS_CDN_URLS)) {
data = OssUtils.downloadFile2Byte(url);
// } else if (url.contains("/group")) {
// Map<String, String> paramMap = FdfsUtils.splitFilePath(url);
// data =
// FdfsUtils.download(paramMap.get(FdfsEnum.GROUP_NAME.value),
// paramMap.get(FdfsEnum.FILE_ID.value));
} else {
URL httpurl = new URL(url);
data = IOUtils.toByteArray(httpurl);
}
} catch (Exception e) {
LOGGER.error("【文件API】下载文件.[toByteArray]:" + e.getMessage(), e);
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
}
return data;
}
/**
* InputStream
*/
@Deprecated
public static InputStream downloadStreamFromUrl(String url) throws FileException {
try {
URL httpurl = new URL(url);
return httpurl.openStream();
} catch (Exception e) {
LOGGER.error("【文件API】下载文件.[openStream]:" + e.getMessage(), e);
throw new FileException(FileException.FILE_DOWNLOAD_FAILURE, "下载文件失败");
}
}
/**
* 普通情况下保存字节数据到本地文件
*/
public synchronized static boolean saveBytesTofile(File file, byte[] data) throws BizException {
FileOutputStream fos = null;
// 建立输出字节流
try {
fos = new FileOutputStream(file);
fos.write(data); // 用FileOutputStream 的write方法写入字节数组
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 复制一个文件到另一个目录下
*
* @throws BizException
*/
public static void copyFileToFolder(File inputFile, File outputFile) throws BizException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(inputFile);
fos = new FileOutputStream(outputFile);
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) {
ioe.printStackTrace();
}
}
/**
* 合并两个文件
*
* @param outFile 目标文件
* @param leafFile 源文件
*/
public static void mergeFiles(File outFile, File leafFile) {
FileOutputStream fos = null;
FileInputStream fis = null;
if (!outFile.exists()) {
try {
outFile.createNewFile();
} catch (Exception e) {
throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败");
}
}
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);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
if (fos != null)
fos.close();
} catch (Exception e) {
}
}
}
/**
* 合并多个文件
*
* @param outFile 输出文件,
* @param leafFiles 文件碎片集
*/
public static void mergeFileList(File outFile, List<File> leafFiles) {
FileOutputStream fos = null;
FileInputStream fis = null;
if (!outFile.exists()) {
try {
outFile.createNewFile();
} catch (Exception e) {
throw new FileException(FileException.FILE_NOT_EXIST, "创建临时存储文件失败");
}
}
try {
// 合并其实就是文件的续写,写成true
fos = new FileOutputStream(outFile, true);
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);
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
if (fos != null)
fos.close();
} catch (Exception e) {
}
}
}
/**
* 音频文件转换
*
* @param data 音频byte数组
* @param sourExt 原始后缀
* @param ext 新后缀
* @return
* @author PENG
*/
public static String audioFormatConvert(byte[] data, String sourExt, String ext) {
File tmpdir = new File("tempdir/local");
if (!tmpdir.exists()) {
try {
tmpdir.mkdirs();
} catch (SecurityException ex) {
System.out.println("无法创建临时文件夹");
ex.printStackTrace();
}
}
String name = UUID.randomUUID().toString();
File source = new File(tmpdir, name + "." + sourExt);
boolean creat = saveBytesTofile(source, data);
if (creat) {
File target = new File(tmpdir, name + "." + ext);
AudioAttributes audio = new AudioAttributes();
Encoder encoder = new Encoder();
audio.setCodec("libmp3lame");
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat(ext.toLowerCase());
attrs.setAudioAttributes(audio);
try {
encoder.encode(source, target, attrs);
return target.getPath();
} catch (IllegalArgumentException e) {
e.printStackTrace();
return null;
} catch (InputFormatException e) {
e.printStackTrace();
return null;
} catch (EncoderException e) {
e.printStackTrace();
return target.getPath();
}
} else {
return null;
}
}
/**
* 获取文本的内容
*
* @param url
* @return
*/
public static String getTextString(String url) {
LOGGER.info("【文件API】获取文本的内容.<START>.[url]=" + url);
if (StringUtil.isEmpty(url)) {
return null;
}
StringBuilder lrcString = new StringBuilder();
InputStream is = 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");
} else {
Object charSet = CpdetectorEncoding.getEncoding(bt, false);
if (charSet.toString().equals("UTF-8")) {
isr = new InputStreamReader(is, "UTF-8");
} else {
isr = new InputStreamReader(new ByteArrayInputStream(bt), "GBK");
}
}
BufferedReader br = new BufferedReader(isr);// 构造一个BufferedReader类来读取文件
String s;
while ((s = br.readLine()) != null) {// 使用readLine方法,一次读一行
lrcString.append(System.lineSeparator() + s);
}
} catch (Exception e) {
LOGGER.error("【文件工具】读取文件内容.<ERROR>:" + e.getMessage(), e);
} finally {
try {
if (isr != null)
isr.close();
if (is != null)
is.close();
} catch (Exception e2) {
}
}
LOGGER.info("【文件API】获取文本的内容.<END>");
return lrcString.toString();
}
/**
* java 8 读取文本内容
*
* @param url
* @return
*/
public static String getTextString8(String url) {
LOGGER.info("【文件API】获取文本的内容8.<START>.[url]=" + url);
StringBuilder result = new StringBuilder();
String fileType = getFileType(url);
String localFilePath = url;
if (url.startsWith("http")) {
localFilePath = FilePathConst.TEXT_PATH + UUIDUitl.taskName() + "." + fileType;
downloadFileFromUrl(url, localFilePath);
}
try {
Stream<String> lines = Files.lines(Paths.get(localFilePath), StandardCharsets.UTF_8);
lines.forEach(line -> {
result.append(line + System.lineSeparator());
});
lines.close();
} catch (Exception e) {
LOGGER.error("【文件工具】读取文件内容8.<ERROR>:" + e.getMessage(), e);
} finally {
deleteFile(localFilePath);
}
LOGGER.info("【文件API】获取文本的内容8.<END>");
return result.toString();
}
/**
* 文件剪切,网络路径、按文件大小的百分比
*
* @param url
* @param percent
* 1~100的整数
* @return 返回剪切后上传后的文件路径
* @throws BizException
*/
public static String clipByPercent(String url, int percent) throws BizException {
LOGGER.info("【文件API】文件剪切,按百分比.<START>.[url]=" + url);
if (StringUtil.isEmpty(url)) {
return null;
}
String fileType = FileUtils.getFileType(url);
if (!FileUtils.VIDEO.equals(FileUtils.getGatherName(fileType))) {
return null;
}
// 下载文件
String downloadPath = FilePathConst.DOWNLOAD_PATH + UUIDUitl.generateString(32) + "." + fileType;
FileUtils.downloadFileFromUrl(url, downloadPath);
// 剪切文件
String cutPath = clipByPercent(new File(downloadPath), percent);
// 重新上传文件
UploadResultInfo uploadResultInfo = OssUtils.uploadLocalFile(cutPath, null);
// 删除本地文件
FileUtils.deleteFile(downloadPath);
FileUtils.deleteFile(cutPath);
LOGGER.info("【文件API】文件剪切,按百分比.<END>.[uploadResultInfo]=" + uploadResultInfo);
return uploadResultInfo == null ? null : uploadResultInfo.getUrl();
}
/**
* 文件剪切,本地路径、按百分比
*
* @param inputFile
* @param cutPercent
* 1~100的整数
* @return 返回本地路径地址
* @throws BizException
*/
public static String clipByPercent(File inputFile, int cutPercent) throws BizException {
LOGGER.info("【文件API】文件剪切.<START>.[cutPercent]=" + cutPercent);
if (inputFile == null || inputFile.length() <= 0) {
throw new FileException(FileException.FILE_NOT_EXIST, "不是有效的文件");
}
if (cutPercent > 100 || cutPercent < 1) {
throw new FileException(FileException.FILE_READ_FAILURE, "百分比必须是1~100之间的整数");
}
return clipByLength(inputFile, Math.round(inputFile.length() * cutPercent / 100.0d));
}
/**
* 文件剪切
*
* @param inputFile
* 待剪切的文件
* @param cutLength
* 剪切长度(Byte)
*/
public static String clipByLength(File inputFile, long cutLength) throws BizException {
LOGGER.info("【文件API】文件剪切.<START>.[cutLength]=" + cutLength);
if (inputFile == null || inputFile.length() <= 0) {
throw new FileException(FileException.FILE_NOT_EXIST, "不是有效的文件");
}
if (cutLength < 1024) {
throw new FileException(FileException.FILE_READ_FAILURE, "剪切的文件必须大于1KB");
}
// 输出文件路径
String outFilePath = FilePathConst.CUT_PATH + UUIDUitl.generateString(12) + "_" + inputFile.getName();
creatFiles(outFilePath);
// 剪切长度
cutLength = cutLength > inputFile.length() ? inputFile.length() : cutLength;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
// 两个输入流
bis = new BufferedInputStream(new FileInputStream(inputFile));
// 缓冲字节输出流
bos = new BufferedOutputStream(new FileOutputStream(outFilePath));
// 读取多少次
long index = cutLength % 1024 > 0 ? cutLength / 1024 + 1 : cutLength / 1024;
int mod = (int) cutLength % 1024;
byte[] bt = new byte[1024];
int len = 0;
for (int i = 0; i < index; i++) {
if (i + 1 == index && mod != 0) {
bt = new byte[mod];
len = bis.read(bt);
} else {
len = bis.read(bt);
}
if (len != -1) {
bos.write(bt, 0, len);
}
}
bos.flush();
} catch (IOException e) {
LOGGER.error("【文件工具】剪切文件内容:" + e.getMessage(), e);
throw new FileException(FileException.FILE_READ_FAILURE, "文件剪切失败");
} finally {
try {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
} catch (IOException e) {
LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e);
}
}
LOGGER.info("【文件API】文件剪切.<END>");
return outFilePath;
}
/**
* 将文件转成base64 字符串
*
* @param data
* @return *
* @throws Exception
*/
public static String encodeBase64File(byte[] data) throws BizException {
try {
return new String(Base64.encodeBase64(data));
} catch (Exception e) {
LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e);
return null;
}
}
/**
* 将base64字符解码保存文件
*
* @param base64Code
* @param targetPath
* @throws Exception
*/
public static boolean decoderBase64File(String base64Code, String targetPath) throws BizException {
if (base64Code == null)
return false;
OutputStream out = null;
try {
// Base64解码
byte[] b = Base64.decodeBase64(targetPath);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成jpeg图片
out = new FileOutputStream(targetPath);
out.write(b);
out.flush();
} catch (Exception e) {
LOGGER.error("【文件工具】将base64字符解码保存文件失败:" + e.getMessage(), e);
return false;
} finally {
try {
if (out != null)
out.close();
} catch (Exception e) {
}
}
return true;
}
/**
* 本地文件到byte数组
*
* @param path
* @return
*/
public static byte[] file2byte(String path) {
byte[] data = null;
FileInputStream fis = null;
ByteArrayOutputStream os = null;
try {
fis = new FileInputStream(new File(path));
os = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int numBytesRead = 0;
while ((numBytesRead = fis.read(buf)) != -1) {
os.write(buf, 0, numBytesRead);
}
data = os.toByteArray();
} catch (Exception e) {
LOGGER.error("【文件工具】文件到byte数组:" + e.getMessage(), e);
} finally {
try {
if (fis != null)
fis.close();
if (os != null)
os.close();
} catch (IOException e) {
LOGGER.error("【文件工具】文件流关闭失败:" + e.getMessage(), e);
}
}
return data;
}
/**
* 从输入流中获取数据
*
* @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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dcg.util.StringUtils;
import com.itextpdf.text.Image;
import com.pcloud.common.constant.AliyunConstant;
import com.pcloud.common.constant.FilePathConst;
import com.pcloud.common.constant.ImageConstant;
import com.pcloud.common.entity.UploadResultInfo;
import com.pcloud.common.enums.ImageEnum;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.FileException;
......@@ -688,4 +691,37 @@ public class ImageUtils {
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 {
header.put("Content-Type", "application/json");
Map<String,String>param = new HashMap<>();
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);
String pic = (String)map.get("data");
BufferedImage bookPicImage = ImageIO.read(new URL(pic));
......
......@@ -21,6 +21,7 @@ import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -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 onColor
......
......@@ -17,43 +17,63 @@ import com.pcloud.common.page.PageBeanNew;
*/
public class ResultUtils {
/**
* 集合查询结果判断
*
* @param lists
* @return
*/
public static <T> List<T> list(List<T> lists) {
if (!ListUtils.isEmpty(lists)) {
return lists;
}
return Lists.newArrayList();
}
/**
* map查询结果判断
*
* @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());
}
/**
* 单个对象实例化
*
* @param t
* @param clazz
* @return
* @author songx
* @date 2019年1月14日,下午7:32:35
*/
public static <T> T object(T t, Class<T> clazz) {
if (t == null) {
return null;
}
try {
return clazz.newInstance();
} catch (Exception e) {
}
return null;
}
/**
* 集合查询结果判断
*
* @param lists
* @return
*/
public static <T> List<T> list(List<T> lists) {
if (!ListUtils.isEmpty(lists)) {
return lists;
}
return Lists.newArrayList();
}
/**
* map查询结果判断
*
* @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;
import org.slf4j.LoggerFactory;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.NumberUtil;
import com.pcloud.common.utils.string.StringUtil;
/**
......@@ -125,25 +126,25 @@ public class Cookie {
String[] channel = userInfoArry[i].split("=");
String channelId = channel[channel.length - 1];
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")) {
String[] wechat = userInfoArry[i].split("=");
String officialAccountsId = wechat[wechat.length - 1];
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")) {
String[] user = userInfoArry[i].split("=");
String wechatUserId = user[user.length - 1];
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")) {
String[] party = userInfoArry[i].split("=");
String partyId = party[party.length - 1];
userInfos.put("partyId", StringUtil.isEmpty(partyId) || "undefined".equalsIgnoreCase(partyId) || "null".equalsIgnoreCase(partyId)
? null : Long.valueOf(partyId));
? null : NumberUtil.toLong(partyId));
}
// editBy TC cookie里面需要带上顾问,systemCode,是否系统,场景值
// modify by songx at 2017-05-17 如果值为undefined或者null直接跳过
......@@ -151,7 +152,7 @@ public class Cookie {
String[] adviser = userInfoArry[i].split("=");
String adviserId = adviser[adviser.length - 1];
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")) {
String[] systemCode = userInfoArry[i].split("=");
......@@ -168,25 +169,25 @@ public class Cookie {
String[] scene = userInfoArry[i].split("=");
String sceneId = scene[scene.length - 1];
userInfos.put("sceneId", StringUtil.isEmpty(sceneId) || "undefined".equalsIgnoreCase(sceneId) || "null".equalsIgnoreCase(sceneId) ? null
: Long.valueOf(sceneId));
: NumberUtil.toLong(sceneId));
}
if (userInfoArry[i].contains("userId")) {
String[] userLogin = userInfoArry[i].split("=");
String userId = userLogin[userLogin.length - 1];
userInfos.put("userId", StringUtil.isEmpty(userId) || "undefined".equalsIgnoreCase(userId) || "null".equalsIgnoreCase(userId) ? null
: Long.valueOf(userId));
: NumberUtil.toLong(userId));
}
if (userInfoArry[i].contains("merchantMemberId")) {
String[] merchant = userInfoArry[i].split("=");
String merchantMemberId = merchant[merchant.length - 1];
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")) {
String[] merchant = userInfoArry[i].split("=");
String agentMemberId = merchant[merchant.length - 1];
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
if (userInfoArry[i].contains(PREVIEW_TYPE)) {
......@@ -205,13 +206,13 @@ public class Cookie {
String[] firstTD = userInfoArry[i].split("=");
String code = firstTD[firstTD.length - 1];
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)) {
String[] secondTD = userInfoArry[i].split("=");
String code = secondTD[secondTD.length - 1];
userInfos.put(SECOND_TD, StringUtil.isEmpty(code) || "undefined".equalsIgnoreCase(code) || "null".equalsIgnoreCase(code) ? null
: Long.valueOf(code));
: NumberUtil.toLong(code));
}
}
return userInfos;
......@@ -226,7 +227,7 @@ public class Cookie {
*/
public static Long getId(String userInfo, String type) throws BizException {
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 {
}
/**
* 生成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
* @author linweibin
......
package com.pcloud.common.utils.httpclient;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pcloud.common.utils.rsa.MD5;
import com.pcloud.common.utils.string.StringUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* @author:songx
* @date:2017年12月4日,下午4:58:39
*/
public class UrlUtils {
/**
*
*/
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=";
/**
* 请求地址(OWN)
*/
private static final String REQUEST_URL2 = "https://rays.5rs.me/convert/v1.0/url/shorten";
/**
* 获取短链接(新浪)
*
* @param long_url
* @return
*/
public static String getShortUrl(String long_url) {
String result = callHttp(long_url);
if (StringUtil.isEmpty(result)) {
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();
HttpGet httpGet = new HttpGet(REQUEST_URL + long_url);
String resContent = null;
try {
CloseableHttpResponse response = httpclient.execute(httpGet);
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
resContent = EntityUtils.toString(entity);
}
} catch (IOException e) {
LOGGER.error("【URL】短链接转换失败(新浪):" + e.getMessage(), e);
}
LOGGER.info("【URL】短链接转换(新浪),<END>.[resContent]=" + resContent);
return resContent;
}
/**
* 获取短链接(OWN)
*
* @param long_url
* @return
*/
public static String getShortUrl4Own(String long_url) {
String result = callHttp4Own(long_url);
if (StringUtil.isEmpty(result)) {
return null;
}
JSONObject resultObject = JSONObject.parseObject(result);
JSONObject dataObject = resultObject.getJSONObject("data");
return dataObject == null ? null : dataObject.getString("shortUrl");
}
/**
* 发送请求(OWN)
*
* @param long_url
* @return
*/
private static String callHttp4Own(String long_url) {
LOGGER.info("【URL】短链接转换(OWN),<START>.[long_url]=" + long_url);
if (StringUtil.isEmpty(long_url)) {
return null;
}
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(REQUEST_URL2);
String resContent = null;
try {
//设置参数到请求对象中
JSONObject jsonObject = new JSONObject();
jsonObject.put("originUrl", long_url);
StringEntity stringEntity = new StringEntity(jsonObject.toJSONString(), Charset.forName("UTF-8"));
httpPost.setEntity(stringEntity);
//设置header信息
//指定报文头【Content-type】、【User-Agent】
httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
CloseableHttpResponse response = httpclient.execute(httpPost);
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
resContent = EntityUtils.toString(entity);
}
} 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";
// 要使用生成 URL 的字符
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",
"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"
};
// 对传入网址进行 MD5 加密
String hex = MD5.getMD5Str(key + url);
String[] resUrl = new String[4];
for (int i = 0; i < 4; i++) {
// 把加密字符按照 8 位一组 16 进制与 0x3FFFFFFF 进行位与运算
String sTempSubString = hex.substring(i * 8, i * 8 + 8);
// 这里需要使用 long 型来转换,因为 Inteper .parseInt() 只能处理 31 位 , 首位为符号位 ,
// 如果不用long ,则会越界
long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16);
String outChars = "";
for (int j = 0; j < 7; j++) {
// 把得到的值与 0x0000003D 进行位与运算,取得字符数组 chars 索引
long index = 0x0000003D & lHexLong;
// 把取得的字符相加
outChars += chars[(int) index];
// 每次循环按位右移 4 位
lHexLong = lHexLong >> 4;
}
// 把字符串存入对应索引的输出数组
resUrl[i] = outChars;
}
return resUrl;
}
}
package com.pcloud.common.utils.httpclient;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pcloud.common.utils.rsa.MD5;
import com.pcloud.common.utils.string.StringUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* @author:songx
* @date:2017年12月4日,下午4:58:39
*/
public class UrlUtils {
/**
*
*/
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=";
/**
* 请求地址(OWN)
*/
private static final String REQUEST_URL2 = "https://rays.5rs.me/convert/v1.0/url/shorten";
/**
* 自定义生成 MD5 加密字符传前的混合 KEY
*/
public static final String PRIVATE_KEY = "lgsc1205";
/**
* 获取短链接(新浪)
*
* @param long_url
* @return
*/
public static String getShortUrl(String long_url) {
String result = callHttp(long_url);
if (StringUtil.isEmpty(result)) {
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();
HttpGet httpGet = new HttpGet(REQUEST_URL + long_url);
String resContent = null;
try {
CloseableHttpResponse response = httpclient.execute(httpGet);
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
resContent = EntityUtils.toString(entity);
}
} catch (IOException e) {
LOGGER.error("【URL】短链接转换失败(新浪):" + e.getMessage(), e);
}
LOGGER.info("【URL】短链接转换(新浪),<END>.[resContent]=" + resContent);
return resContent;
}
/**
* 获取短链接(OWN)
*
* @param long_url
* @return
*/
public static String getShortUrl4Own(String long_url) {
String result = callHttp4Own(long_url);
if (StringUtil.isEmpty(result)) {
return null;
}
JSONObject resultObject = JSONObject.parseObject(result);
JSONObject dataObject = resultObject.getJSONObject("data");
return dataObject == null ? null : dataObject.getString("shortUrl");
}
/**
* 发送请求(OWN)
*
* @param long_url
* @return
*/
private static String callHttp4Own(String long_url) {
LOGGER.info("【URL】短链接转换(OWN),<START>.[long_url]=" + long_url);
if (StringUtil.isEmpty(long_url)) {
return null;
}
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(REQUEST_URL2);
String resContent = null;
try {
// 设置参数到请求对象中
JSONObject jsonObject = new JSONObject();
jsonObject.put("originUrl", long_url);
StringEntity stringEntity = new StringEntity(jsonObject.toJSONString(), Charset.forName("UTF-8"));
httpPost.setEntity(stringEntity);
// 设置header信息
// 指定报文头【Content-type】、【User-Agent】
httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
CloseableHttpResponse response = httpclient.execute(httpPost);
// 获取响应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
resContent = EntityUtils.toString(entity);
}
} 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 加密
String hex = MD5.getMD5Str(PRIVATE_KEY + url);
return shortenUrlMd5(hex);
}
/**
* 缩短链接
*
* @param url
* @return
*/
public static String[] shortenUrlMd5(String hex) {
// 要使用生成 URL 的字符
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",
"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" };
String[] resUrl = new String[4];
for (int i = 0; i < 4; i++) {
// 把加密字符按照 8 位一组 16 进制与 0x3FFFFFFF 进行位与运算
String sTempSubString = hex.substring(i * 8, i * 8 + 8);
// 这里需要使用 long 型来转换,因为 Inteper .parseInt() 只能处理 31 位 , 首位为符号位 ,
// 如果不用long ,则会越界
long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16);
String outChars = "";
for (int j = 0; j < 7; j++) {
// 把得到的值与 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;
import com.pcloud.common.utils.string.StringUtil;
/**
* MD5
*/
......@@ -66,9 +64,22 @@ public class MD5 {
else
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字符串,全小写
*
......@@ -111,9 +122,9 @@ public class MD5 {
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(DigestUtils.md5Hex("chenjianhua").toUpperCase());
}
}
......@@ -613,7 +613,26 @@ public class StringTools {
* @param array
* @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) {
return false;
}
......
......@@ -120,8 +120,8 @@ public class CompressUtils {
if (ListUtils.isEmpty(fileUrlList)) {
return null;
}
zipName = FileUtils.formatName(zipName);
String tempZipName = zipName + "_" + LocalDateUtils.getYmdhmss();
String zipNameFormat = FileUtils.formatName(zipName);
String tempZipName = zipNameFormat + "_" + LocalDateUtils.getYmdhmss();
String zipFilePath = ZIP_FILE_PATH + tempZipName + ".zip";
// 检查临时文件夹是否存在,不存在就创建
String fileFolderPath = FILE_LOCAL_PATH + tempZipName;
......@@ -141,7 +141,7 @@ public class CompressUtils {
FileUtils.isDir(ZIP_FILE_PATH);
CompressUtils.zip(fileFolderPath, zipFilePath);
// 上传文件到服务器中
uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipName);
uploadResultInfo = OssUtils.uploadLocalFile4CustomName(zipFilePath, zipNameFormat);
uploadResultInfo.setFileName(zipName);
} catch (Exception 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.util.Calendar;
......
package com.pcloud.common.utils.solr;
package com.pcloud.solr;
import java.util.List;
import java.util.Map;
......
package com.pcloud.common.utils.solr;
package com.pcloud.solr;
import java.io.Serializable;
import java.util.List;
......@@ -8,7 +8,7 @@ import java.util.List;
* @author PENG
* @date 2018/4/24
*/
public class SolrResult implements Serializable {
public class SolrResult<T> implements Serializable {
private static final long serialVersionUID = 1195918725820896691L;
......@@ -25,7 +25,7 @@ public class SolrResult implements Serializable {
/**
* 查询结果列表
*/
private List<SolrDto> list;
private List<T> list;
public Integer getTotalCount() {
return totalCount;
......@@ -43,11 +43,11 @@ public class SolrResult implements Serializable {
this.maxScore = maxScore;
}
public List<SolrDto> getList() {
public List<T> getList() {
return list;
}
public void setList(List<SolrDto> list) {
public void setList(List<T> list) {
this.list = list;
}
......
package com.pcloud.common.utils.solr;
package com.pcloud.solr;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
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.SolrQuery;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
......@@ -21,8 +23,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
/**
* Description solr全文检索工具类
......@@ -39,7 +39,7 @@ public class SolrUtils {
private static String defaultCollection;
private static CloudSolrClient solrClient;
protected static CloudSolrClient solrClient;
/**
* 新增或修改索引(id主键存在时为更新)
......@@ -52,6 +52,15 @@ public class SolrUtils {
/**
* 新增或修改索引(id主键存在时为更新)
* @param object solr索引DTO
* @return 是否成功
*/
public static Boolean addObject(Object object) {
return addObject(getDefaultCollection(), object);
}
/**
* 新增或修改索引(id主键存在时为更新)
* @param collection 索引集
* @param solrDto solr索引DTO
* @return 是否成功
......@@ -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主键存在时为更新)
* @param list solr索引DTO列表
* @return 是否成功
......@@ -78,6 +104,15 @@ public class SolrUtils {
/**
* 批量新增或修改索引(id主键存在时为更新)
* @param list solr索引DTO列表
* @return 是否成功
*/
public static Boolean addObject(List<Object> list) {
return addObject(getDefaultCollection(), list);
}
/**
* 批量新增或修改索引(id主键存在时为更新)
* @param collection 索引集
* @param list solr索引DTO列表
* @return 是否成功
......@@ -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主键删除索引
* @param id id主键
* @return 是否成功
......@@ -156,6 +208,15 @@ public class SolrUtils {
/**
* 根据id主键获取索引
* @param id id主键
* @return SolrDto
*/
public static SolrDocument getObjectById(String id) {
return getObjectById(getDefaultCollection(), id);
}
/**
* 根据id主键获取索引
* @param collection 索引集
* @param id id主键
* @return SolrDto
......@@ -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主键列表批量获取索引
* @param ids id主键列表
* @return SolrDto Map
......@@ -185,13 +261,22 @@ public class SolrUtils {
/**
* 根据id主键列表批量获取索引
* @param ids id主键列表
* @return SolrDto Map
*/
public static Map<String, SolrDocument> mapObjectByIds(List<String> ids) {
return mapObjectByIds(getDefaultCollection(), ids);
}
/**
* 根据id主键列表批量获取索引
* @param collection 索引集
* @param ids id主键列表
* @return SolrDto Map
*/
public static Map<String, SolrDto> getById(String collection, List<String> ids) {
try {
if (ListUtils.isEmpty(ids)) {
if (null == ids || ids.isEmpty()) {
return null;
}
SolrDocumentList documents = solrClient.getById(collection, ids);
......@@ -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 查询参数
* @return SolrResult
......@@ -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 param 查询参数
* @return SolrResult
*/
public static SolrResult search(String collection, SolrQueryParam param) {
public static SolrResult<SolrDto> search(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 solrResult = new SolrResult();
SolrResult<SolrDto> solrResult = new SolrResult<SolrDto>();
solrResult.setTotalCount(Integer.parseInt(documents.getNumFound() + ""));
solrResult.setMaxScore(documents.getMaxScore());
List<SolrDto> list = new ArrayList<>();
......@@ -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
* @param document solr文档
* @return SolrDto
......@@ -287,7 +436,7 @@ public class SolrUtils {
* @param param solr查询参数
* @return SolrQuery
*/
private static SolrQuery formatQueryParam(SolrQueryParam param) {
protected static SolrQuery formatQueryParam(SolrQueryParam param) {
SolrQuery solrQuery = new SolrQuery();
if (null == param) {
param = new SolrQueryParam();
......@@ -297,7 +446,7 @@ public class SolrUtils {
} else {
solrQuery.set("q", "*:*");
}
if (!ListUtils.isEmpty(param.getFq())) {
if (null != param.getFq() && !param.getFq().isEmpty()) {
for (String fq : param.getFq()) {
solrQuery.addFilterQuery(fq);
}
......@@ -353,7 +502,7 @@ public class SolrUtils {
*/
public static String getUTCShortDateStr() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(DateUtils.dateFormat(new Date()));
calendar.setTime(dateFormat(new Date()));
calendar.add(Calendar.HOUR_OF_DAY, -8);
return UTC_FULL_DATE_FORMAT.format(calendar.getTime());
}
......@@ -365,15 +514,31 @@ public class SolrUtils {
*/
public static String formatUTCShortDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(DateUtils.dateFormat(date));
calendar.setTime(dateFormat(date));
calendar.add(Calendar.HOUR_OF_DAY, -8);
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();
}
......
......@@ -18,6 +18,7 @@
<module>pcloud-common-config</module>
<module>pcloud-common</module>
<module>pcloud-common-core</module>
<module>pcloud-solr</module>
</modules>
<packaging>pom</packaging>
......@@ -47,6 +48,7 @@
<pcloud-common.version>2.1.0-RELEASE</pcloud-common.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-solr.version>2.1.0-RELEASE</pcloud-solr.version>
</properties>
</profile>
<!-- 压测环境 -->
......@@ -68,6 +70,7 @@
<pcloud-common.version>2.1.0-RELEASE</pcloud-common.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-solr.version>2.1.0-RELEASE</pcloud-solr.version>
</properties>
</profile>
<!-- 生产环境 RAYS -->
......@@ -89,6 +92,7 @@
<pcloud-common.version>2.1.1-RELEASE</pcloud-common.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-solr.version>2.1.1-RELEASE</pcloud-solr.version>
</properties>
</profile>
</profiles>
......@@ -227,6 +231,11 @@
<version>4.4.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
......@@ -303,13 +312,6 @@
</dependency>
<!-- 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 -->
<dependency>
<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