Commit b81c7945 authored by 曹志's avatar 曹志

公共模块

parent 7f26fb9f
......@@ -6,6 +6,7 @@
<modules>
<module>spacetech-common-util</module>
<module>spacetech-service-interface</module>
<module>spacetech-service-growth</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
......@@ -45,5 +46,32 @@
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>nexus</id>
<name>Team Nexus Repository</name>
<!-- <url>http://weixt.spacetech.com.cn:8081/nexus/content/groups/public</url> -->
<url>http://weixt.spacetech.com.cn:9091/nexus/content/groups/public</url>
</repository>
<repository>
<id>snapshot</id>
<name>公司内部开发用的jar lib</name>
<url>http://weixt.spacetech.com.cn:9091/nexus/content/repositories/snapshots</url>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>releases1</id>
<name>Team Nexus Repository</name>
<url>http://weixt.spacetech.com.cn:9091/nexus/content/groups/releases/</url>
</repository>
<snapshotRepository>
<id>snapshots</id>
<name>Nexus Snapshot Repository</name>
<url>http://weixt.spacetech.com.cn:9091/nexus/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>
......@@ -31,5 +31,155 @@
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--阿里云OSS存储-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.0.6</version>
<exclusions>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 生成二维码 -->
<dependency>
<groupId>com.google</groupId>
<artifactId>zxing-core</artifactId>
<version>1.0.0</version>
</dependency>
<!--JDOM 解析XML依赖包-->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>2.0.2</version>
</dependency>
<!--百度AI开放平台-->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.12.0</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--POI 处理Excel文档-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
<scope>compile</scope>
</dependency>
<!--百度云SDK开发包-->
<dependency>
<groupId>com.baidubce</groupId>
<artifactId>bce-java-sdk</artifactId>
<version>0.10.78</version>
</dependency>
<!--异步HTTP客户端开发包-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.0.2</version>
</dependency>
<!--SpringData JPA-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--日期时间处理库-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.4</version>
</dependency>
<!--图片压缩工具-->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<!--java操作Excel表格工具包-->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
<!--汉语拼音工具库-->
<dependency>
<groupId>net.sourceforge.pinyin4j</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
<!-- MEMCACHED CLIENT -->
<dependency>
<groupId>com.googlecode.xmemcached</groupId>
<artifactId>xmemcached</artifactId>
<version>2.0.0</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<!--Memcache 客户端-->
<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.11.2</version>
</dependency>
<!--Servlet API-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!--zookeeper 客户端工具包-->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
<!--自定义工具包[fastjson,StringUtils]-->
<dependency>
<groupId>ground</groupId>
<artifactId>sdk_release_gs1</artifactId>
<version>1.51.61</version>
</dependency>
<!-- nacos-client -->
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.spacetech.common;
public class ConstantVar {
public static final String SPACE_PLACEHOLDER = "spaceplaceholder";
/******************** dubbo所用常量 ***************************/
/**
* 用户类型-老师
*/
public static final int USER_TYPE_TEACHER = 1;
/**
* 用户类型-学生
*/
public static final int USER_TYPE_PARENT = 2;
/**
* 用户类型-游客
*/
public static final int USER_TYPE_TOURIST = 0;
public static final String USER_ROLE_SUPERADMIN = "superAdmin";
public static final String USER_ROLE_USER = "user";
public static final String USER_ROLE_ADMIN = "admin";
public static final String USER_ROLE_LEADER = "leader";
public static final String USER_ROLE_ASSISTANT = "assistant";
public static final String USER_ROLE_DIETICIAN = "dietician";// 营养师
public static String VERSION = "3.0";
public static String RAP_URL = "http://10.10.10.190:8280/rap.plugin.js";
public static String RAP_MODE = "3";
/*************************** PUSH 参数 *********************************/
/**
* 状态在用1
*/
public static final int STATE_OPEN = 1;
/**
* 状态1 在用,0停用
*/
public static final int STATE_STOP = 0;
/**
* 性别-男
*/
public static final int SEX_BOY = 1;
public static final String SEX_CH_BOY = "男";
/**
* 性别-女
*/
public static final int SEX_GIRL = 2;
public static final String SEX_CH_GIRL = "女";
/**
* 默认头像-男
*/
public static final String PORTRAIT_BOY = "http://qiniu.weixiaotong.com/boyteacher.jpg";
/**
* 默认头像-女
*/
public static final String PORTRAIT_GIRL = "http://qiniu.weixiaotong.com/girlteacher.jpg";
public static final String KEY_ERROR_CODE = "errcode";
public static final String KEY_ERROR_MSG = "errmsg";
public static final String AES_KEY = "J90a*&j_~!ks^T4j";
public static final String STR_SPLIT = "::::::::::";
public static final String STR_SPLIT_SHORT = ":::";
public static final String STR_SPLIT_4 = "::::";
public static final String CHANNEL_TYPE_CRM = "crm";// crm
public static final String CHANNEL_TYPE_TEMPLATE = "template";// 模版推送
public static final String CHANNEL_TYPE_PHONESMS = "phoneSMS";// 短信通道
public static final String CHANNEL_TYPE_YIXIN_CRM = "yixinCRM";// 易信通道
public static final String CHANNEL_TYPE_WXPOSTFILE = "wxPostFile";// 易信通道
public static final String CHANNEL_TYPE_GROUPS = "groups"; // 用户相关管理
public static final String EVENT_SENDMGS = "TEMPLATESENDJOBFINISH";
public static final String EVENT_CLICK = "CLICK";
public static final String EVENT_VIEW = "VIEW";
public static final String EVENT_SUBSCRIBE = "subscribe";
public static final String EVENT_SCAN = "SCAN";
public static final String EVENT_QRSCENE = "qrscene";
public static final String INFO_TYPE_COMPONENT_VERIFY_TICKET = "component_verify_ticket";// 在公众号第三方平台创建审核通过后,微信服务器会向其“授权事件接收URL”每隔10分钟定时推送component_verify_ticket
public static final String INFO_TYPE_COMPONENT_AUTHORIZED = "authorized";// (授权通知)
public static final String INFO_TYPE_COMPONENT_UPDATEAUTHORIZED = "updateauthorized";// (授权更新通知)
public static final String INFO_TYPE_COMPONENT_UNAUTHORIZED = "unauthorized";// (授权更新通知)
public static final Integer CHANNEL_TYPE_YIXIN_CODE = 1;// 易信,当前只有安徽新华幼儿园采用易信
public static final Integer CHANNEL_TYPE_WECHAT_CODE = 0;// 微信
public static final Integer CHANNEL_TYPE_CROP_CODE = 2;// 微信企业号
/** 开关配置参数 */
public static final String CONFIG_VALUE_USED = "1"; // 开通状态
public static final String CONFIG_VALUE_STOP = "0"; // 停用状态
public static final String CONFIG_VALUE_TIME = "15:05:00";
public static final Long CONFIG_CODE_YZXX = 107109l;
public static final String CONFIG_NAME_YZXX = "园长信箱";
public static final String CONFIG_REMARK_YZXX = "对外的园长信箱开启或关闭";
public static final Long CONFIG_CODE_COMMENT_BJQ = 207101404l;
public static final String CONFIG_NAME_COMMENT_BJQ = "班级圈评论开关";
public static final String CONFIG_REMARK_COMMENT_BJQ = "班级圈评论的开启或关闭";
public static final Long CONFIG_CODE_COMMENT_STUDY = 207103104l;
public static final String CONFIG_NAME_COMMENT_STUDY = "课堂动态评论开关";
public static final String CONFIG_REMARK_COMMENT_STUDY = "课堂动态的评论功能的开启或关闭";
// 培训机构,没有食谱。不设置
public static final Long CONFIG_CODE_COMMENT_MZSP = 10710704l;
public static final String CONFIG_NAME_COMMENT_MZSP = "食谱评论开关";
public static final String CONFIG_REMARK_COMMENT_MZSP = "食谱评论的开启或关闭";
// 新闻动态评论的开关
public static final Long CONFIG_CODE_COMMENT_NEWS = 10710301L;
/**
* 是否在考勤机上显示班级名称
*/
public static final Long CONFIG_CODE_SHOWBJNAME_AT_MACHINE = 1030007L;
/**
* 是否需要同步活跃度
*/
public static final Long CONFIG_CODE_SYNACTIVELOG_STATE = 1030008L;
public static final Long CONFIG_CODE_WEBSERVICE_URL = 1030009L;
/**
* 是否需要加水印
*/
public static final Long CONFIG_CODE_WATERMARK_STATE = 1030010L;
/**
* 自定义水印
*/
public static final Long CONFIG_CODE_CUSTOMWATERMARK = 1030028L;
/**
* 是否显示成长档案
*/
public static final Long CONFIG_CODE_CZDA_STATE = 1030011L;
/**
* 是否开启电子班牌功能
*/
public static final Long CONFIG_CODE_CLASS_BRAND = 1030012L;
/**
* 是否开启电子班牌功能
*/
public static final String CAMPUS_CONFIG_WX_2 = "20191119";
// 中小学:教育资讯 培训班:培训资讯
public static final Long CONFIG_CODE_COMMENT_YEZS = 107104204l;
public static final String CONFIG_NAME_COMMENT_YEZS = "育儿知识评论开关";
public static final String CONFIG_REMARK_COMMENT_YEZS = "育儿知识评论的开启或关闭";
public static final String CONFIG_NAME_COMMENT_JYZX = "教育资讯评论开关";
public static final String CONFIG_REMARK_COMMENT_JYZX = "教育资讯评论的开启或关闭";
public static final String CONFIG_NAME_COMMENT_PXZX = "培训资讯评论开关";
public static final String CONFIG_REMARK_COMMENT_PXZX = "培训资讯评论的开启或关闭";
public static final Long CONFIG_CODE_BJQ_TXL = 307102l;
public static final String CONFIG_NAME_BJQ_TXL = "消息中心班级通讯录";
public static final String CONFIG_REMARK_BJQ_TXL = "消息中心对班级通讯录发送消息的权限开启或关闭";
public static final Long CONFIG_CODE_MZSP = 201l;
public static final String CONFIG_NAME_MZSP = "每周食谱";
public static final String CONFIG_CODE_APP_VERSION = "APP_VERSION";
public static final String CONFIG_CODE_APP_DOWNLOAD_URL = "APP_DOWNLOAD_URL";
public static final String CONFIG_CODE_APP_DESCRIPTION = "APP_DESCRIPTION";
public static final String CONFIG_CODE_APP_LASTVERSION = "APP_LASTVERSION";
public static final String CONFIG_CODE_APP_VERSION_FOR_PARENT = "APP_VERSION_FOR_PARENT";
public static final String CONFIG_CODE_APP_DOWNLOAD_URL_FOR_PARENT = "APP_DOWNLOAD_URL_FOR_PARENT";
public static final String CONFIG_CODE_APP_DESCRIPTION_FOR_PARENT = "APP_DESCRIPTION_FOR_PARENT";
public static final String CONFIG_CODE_APP_LASTVERSION_FOR_PARENT = "APP_LASTVERSION_FOR_PARENT";
/**
* 为园长/管理员 每日15:00推送应用统计消息,点击进入应用统计
*/
public static final Long CONFIG_CODE_APP_STATISTICAL = 401L;
public static final String CONFIG_NAME_APP_STATISTICAL = "校长/管理员汇报";
public static final String CONFIG_REMARK_APP_STATISTICAL = "每天18:30微信推送当天的全园老师考勤、应用统计。";
/**
* 为带班老师 每日9:00推送应用提醒消息(学生考勤),点击进入我的学生,每周一9:00推送应用提醒消息(个人信息),点击进入个人中心
*/
public static final Long CONFIG_CODE_APP_REMIND = 402L;
public static final String CONFIG_NAME_MYSTUDENT = "教师汇报";
public static final String CONFIG_REMARK_MYSTUDENT = "每天09:00微信推送当天的学生考勤;每周一09:00微信推送老师的上一周应用统计。";
/**
* 打赏开关
*/
public static final String CONFIG_CODE_REWARD = "1030001";
public static final String CONFIG_DEFAULT_VALUE_REWARD = "1";
/**
* 打赏下限
*/
public static final String CONFIG_CODE_REWARD_MIN = "1030002";
public static final String CONFIG_DEFAULT_VALUE_REWARD_MIN = "1";
/**
* 打赏上限
*/
public static final String CONFIG_CODE_REWARD_MAX = "1030003";
public static final String CONFIG_DEFAULT_VALUE_REWARD_MAX = "2";
/**
* 悬赏下限
*/
public static final String CONFIG_CODE_CASH_MIN = "1030004";
public static final String CONFIG_DEFAULT_VALUE_CASH_MIN = "10";
/**
* 悬赏上限
*/
public static final String CONFIG_CODE_CASH_MAX = "1030005";
public static final String CONFIG_DEFAULT_VALUE_CASH_MAX = "200";
/**
* 考勤时间-早上-开始时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_AM_STARTTIME = 20710501l;
public final static String CONFIG_NAME_ATTENDANCETIME_AM_STARTTIME = "考勤时间上午开始时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_AM_STARTTIME = "09:00:00";
/**
* 考勤时间-早上-结束时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_AM_ENDTIME = 20710502l;
public final static String CONFIG_NAME_ATTENDANCETIME_AM_ENDTIME = "考勤时间上午结束时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_AM_ENDTIME = "11:30:00";
/**
* 考勤时间-下午-开始时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_PM_STARTTIME = 20710503l;
public final static String CONFIG_NAME_ATTENDANCETIME_PM_STARTTIME = "考勤时间下午开始时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_PM_STARTTIME = "13:00:00";
/**
* 考勤时间-下午-结束时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_PM_ENDTIME = 20710504l;
public final static String CONFIG_NAME_ATTENDANCETIME_PM_ENDTIME = "考勤时间下午结束时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_PM_ENDTIME = "17:00:00";
/**
* 考勤时间-晚上-开始时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_NINGHT_STARTTIME = 20710505l;
public final static String CONFIG_NAME_ATTENDANCETIME_NIGHT_STARTTIME = "考勤时间晚上开始时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NIGHTSTARTTIME = "19:00:00";
/**
* 考勤时间-下午-结束时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_NIGHT_ENDTIME = 20710506l;
public final static String CONFIG_NAME_ATTENDANCETIME_NIGHT_ENDTIME = "考勤时间晚上节数时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NIGHT_ENDTIME = "20:00:00";
/**
* 考勤时间-早上-时段一-开始时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_MORNING_ONE_STARTTIME = 20710511l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_MORNING_ONE_STARTTIME = 20710611l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_MORNING_ONE_STARTTIME = "考勤时间老师早上时段一开始时间";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_MORNING_ONE_STARTTIME = "考勤时间学生早上时段一开始时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_MORNING_ONE_STARTTIME = "06:00";
/**
* 考勤时间-早上-时段一-结束时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_MORNING_ONE_ENDTIME = 20710512l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_MORNING_ONE_ENDTIME = 20710612l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_MORNING_ONE_ENDTIME = "考勤时间老师早上时段一结束时间";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_MORNING_ONE_ENDTIME = "考勤时间学生早上时段一结束时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_MORNING_ONE_ENDTIME = "09:00";
/**
* 考勤时间-早上-时段二-开始时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_MORNING_TWO_STARTTIME = 20710521l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_MORNING_TWO_STARTTIME = 20710621l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_MORNING_TWO_STARTTIME = "考勤时间老师早上时段二开始时间";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_MORNING_TWO_STARTTIME = "考勤时间学生早上时段二开始时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_MORNING_TWO_STARTTIME = "09:00";
/**
* 考勤时间-早上-时段二-结束时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_MORNING_TWO_ENDTIME = 20710522l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_MORNING_TWO_ENDTIME = 20710622l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_MORNING_TWO_ENDTIME = "考勤时间老师早上时段二结束时间";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_MORNING_TWO_ENDTIME = "考勤时间学生早上时段二结束时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_MORNING_TWO_ENDTIME = "12:00";
/**
* 考勤时间-下午-时段一-开始时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_NOON_ONE_STARTTIME = 20710531l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_NOON_ONE_STARTTIME = 20710631l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_NOON_ONE_STARTTIME = "考勤时间老师下午时段一开始时间";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_NOON_ONE_STARTTIME = "考勤时间学生下午时段一开始时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NOON_ONE_STARTTIME = "12:00";
/**
* 考勤时间-下午-时段一-结束时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_NOON_ONE_ENDTIME = 20710532l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_NOON_ONE_ENDTIME = 20710632l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_NOON_ONE_ENDTIME = "考勤时间老师下午时段一结束时间";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_NOON_ONE_ENDTIME = "考勤时间学生下午时段一结束时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NOON_ONE_ENDTIME = "15:00";
/**
* 考勤时间-下午-时段二-开始时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_NOON_TWO_STARTTIME = 20710541l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_NOON_TWO_STARTTIME = 20710641l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_NOON_TWO_STARTTIME = "考勤时间老师下午时段二开始时间";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_NOON_TWO_STARTTIME = "考勤时间学生下午时段二开始时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NOON_TWO_STARTTIME = "15:00";
/**
* 考勤时间-下午-时段二-结束时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_NOON_TWO_ENDTIME = 20710542l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_NOON_TWO_ENDTIME = 20710642l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_NOON_TWO_ENDTIME = "考勤时间老师下午时段二结束时间";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_NOON_TWO_ENDTIME = "考勤时间学生下午时段二结束时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NOON_TWO_ENDTIME = "18:00";
/**
* 考勤时间-晚上-时段一-开始时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_NIGHT_ONE_STARTTIME = 20710551l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_NIGHT_ONE_STARTTIME = 20710651l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_NIGHT_ONE_STARTTIME = "考勤时间老师晚上时段一开始时间";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_NIGHT_ONE_STARTTIME = "考勤时间学生晚上时段一开始时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NIGHT_ONE_STARTTIME = "18:00";
/**
* 考勤时间-晚上-时段一-结束时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_NIGHT_ONE_ENDTIME = 20710552l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_NIGHT_ONE_ENDTIME = 20710652l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_NIGHT_ONE_ENDTIME = "考勤时间老师晚上时段一结束时间";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_NIGHT_ONE_ENDTIME = "考勤时间学生晚上时段一结束时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NIGHT_ONE_ENDTIME = "21:00";
/**
* 考勤时间-晚上-时段二-开始时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_NIGHT_TWO_STARTTIME = 20710561l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_NIGHT_TWO_STARTTIME = 20710661l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_NIGHT_TWO_STARTTIME = "考勤时间老师晚上时段二开始时间";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_NIGHT_TWO_STARTTIME = "考勤时间学生晚上时段二开始时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NIGHT_TWO_STARTTIME = "21:00";
/**
* 考勤时间-晚上-时段二-结束时间
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_NIGHT_TWO_ENDTIME = 20710562l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_NIGHT_TWO_ENDTIME = 20710662l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_NIGHT_TWO_ENDTIME = "考勤时间老师晚上时段二结束时间";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_NIGHT_TWO_ENDTIME = "考勤时间学生晚上时段二结束时间";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NIGHT_TWO_ENDTIME = "22:00";
/**
* 考勤时间-早上-时段一-打卡类型
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_MORNING_ONE_PUNCH_TYPE = 2071051l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_MORNING_ONE_PUNCH_TYPE = 2071061l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_MORNING_ONE_PUNCH_TYPE = "考勤时间老师早上时段一打卡类型";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_MORNING_ONE_PUNCH_TYPE = "考勤时间学生早上时段一打卡类型";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_MORNING_ONE_PUNCH_TYPE = "0";
/**
* 考勤时间-早上-时段二-打卡类型
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_MORNING_TWO_PUNCH_TYPE = 2071052l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_MORNING_TWO_PUNCH_TYPE = 2071062l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_MORNING_TWO_PUNCH_TYPE = "考勤时间老师早上时段二打卡类型";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_MORNING_TWO_PUNCH_TYPE = "考勤时间学生早上时段二打卡类型";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_MORNING_TWO_PUNCH_TYPE = "1";
/**
* 考勤时间-下午-时段一-打卡类型
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_NOON_ONE_PUNCH_TYPE = 2071053l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_NOON_ONE_PUNCH_TYPE = 2071063l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_NOON_ONE_PUNCH_TYPE = "考勤时间老师下午时段一打卡类型";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_NOON_ONE_PUNCH_TYPE = "考勤时间学生下午时段一打卡类型";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NOON_ONE_PUNCH_TYPE = "0";
/**
* 考勤时间-下午-时段二-打卡类型
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_NOON_TWO_PUNCH_TYPE = 2071054l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_NOON_TWO_PUNCH_TYPE = 2071064l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_NOON_TWO_PUNCH_TYPE = "考勤时间老师下午时段二打卡类型";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_NOON_TWO_PUNCH_TYPE = "考勤时间学生下午时段二打卡类型";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NOON_TWO_PUNCH_TYPE = "1";
/**
* 考勤时间-晚上-时段一-打卡类型
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_NIGHT_ONE_PUNCH_TYPE = 2071055l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_NIGHT_ONE_PUNCH_TYPE = 2071065l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_NIGHT_ONE_PUNCH_TYPE = "考勤时间老师晚上时段一打卡类型";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_NIGHT_ONE_PUNCH_TYPE = "考勤时间学生晚上时段一打卡类型";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NIGHT_ONE_PUNCH_TYPE = "0";
/**
* 考勤时间-晚上-时段二-打卡类型
*/
public final static Long CONFIG_CODE_ATTENDANCETIME_TEA_NIGHT_TWO_PUNCH_TYPE = 2071056l;
public final static Long CONFIG_CODE_ATTENDANCETIME_STU_NIGHT_TWO_PUNCH_TYPE = 2071066l;
public final static String CONFIG_NAME_ATTENDANCETIME_TEA_NIGHT_TWO_PUNCH_TYPE = "考勤时间老师晚上时段二打卡类型";
public final static String CONFIG_NAME_ATTENDANCETIME_STU_NIGHT_TWO_PUNCH_TYPE = "考勤时间学生晚上时段二打卡类型";
public final static String CONFIG_DEFAULT_VALUE_ATTENDANCETIME_NIGHT_TWO_PUNCH_TYPE = "1";
/**
* 是否启用短信是否启用消息中心短信通道
*/
public static final Long CONFIG_CODE_SMS = 304L;
/**
* 是否启用刷卡短信通道
*/
public static final Long CONFIG_CODE_SMS_CARD = 305L;
/**
* 是否启用食谱短信通道
*/
public static final Long CONFIG_CODE_SMS_MRCP = 306L;
/**
* 是否启用作业短信通道
*/
public static final Long CONFIG_CODE_SMS_HOMEWORK = 307L;
/**
* 是否启用成绩短信通道
*/
public static final Long CONFIG_CODE_SMS_SCORE = 308L;
/**
* 是否启用短信是否启用短信通道
*/
public static final String CONFIG_NAME_SMS = "是否启用短信";
public static final String CONFIG_REMARK_SMS = "开通短信通道后,将以实际的短信发送量进行月度结算,费用由代理商自行承担,已绑定优先发微信";
/**
* 门户网站同步接口
*/
public static final Long CONFIG_CODE_WEBSTIE = 701L;
public static final String CONFIG_NAME_WEBSTIE = "门户网站同步接口";
public static final String CONFIG_REMARK_WEBSTIE = "微校通新闻、公告、资讯、课堂动态、教师风采数据自动同步至对应门户网站光标移出自动保存";
/**
* 是否开启网站
*/
public static final Long CONFIG_CODE_WEBTEMPLAATE = 403L;
public static final String CONFIG_NAME_WEBTEMPLAATE = "门户群权限开启";
public static final String CONFIG_REMARK_WEBTEMPLAATE = "是否开启网站模版选择。";
public static final Long CONFIG_CODE_CAMERA = 404L;
public static final String CONFIG_NAME_CAMERA = "云看权限开启";
public static final String CONFIG_REMARK_CAMERA = "是否具备接入云看权限。";
public static final String textMsg = "<xml>" + "<ToUserName><![CDATA[%1$s]]></ToUserName>"
+ "<FromUserName><![CDATA[%2$s]]></FromUserName>" + "<CreateTime>%3$s</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>" + "<Content><![CDATA[%4$s]]></Content>" + "<FuncFlag>0</FuncFlag>"
+ "</xml>";
public static final String newsMsg = "<xml>" + "<ToUserName><![CDATA[%1$s]]></ToUserName>"
+ "<FromUserName><![CDATA[%2$s]]></FromUserName>" + "<CreateTime>%3$s</CreateTime>"
+ "<MsgType><![CDATA[news]]></MsgType>" + "<ArticleCount>%4$s</ArticleCount>" + "<Articles>%5$s</Articles>"
+ "<FuncFlag>1</FuncFlag>" + "</xml>";
public static final String newsMsgItem = "<item>" + "<Title><![CDATA[%1$s]]></Title>"
+ "<Description><![CDATA[%2$s]]></Description>" + "<PicUrl><![CDATA[%3$s]]></PicUrl>"
+ "<Url><![CDATA[%4$s]]></Url>" + "</item>";
public static final String eventMsg = "<xml>" + "<ToUserName><![CDATA[%1$s]]></ToUserName>"
+ "<FromUserName><![CDATA[%2$s]]></FromUserName>" + "<CreateTime>%3$s</CreateTime>"
+ "<MsgType><![CDATA[event]]></MsgType>" + "<Event><![CDATA[%4$s]]></Event>"
+ "<EventKey><![CDATA[%5$s]]></EventKey>" + "</xml>";
public static final String linkMsg = "<xml>" + "<ToUserName><![CDATA[%1$s]]></ToUserName>"
+ "<FromUserName><![CDATA[%2$s]]></FromUserName>" + "<CreateTime>%3$s</CreateTime>"
+ "<MsgType><![CDATA[link]]></MsgType>" + "<Title><![CDATA[%4$s]]></Title>"
+ "<Description><![CDATA[%5$s]]></Description>" + "<Url><![CDATA[%6$s]]></Url>" + "<MsgId>%7$s</MsgId>"
+ "</xml>";
public static final String musicMsg = "<xml>" + "<ToUserName><![CDATA[%1$s]]></ToUserName>"
+ "<FromUserName><![CDATA[%2$s]]></FromUserName>" + "<CreateTime>%3$s</CreateTime>"
+ "<MsgType><![CDATA[music]]></MsgType>" + "<Music>" + "<Title><![CDATA[%4$s]]></Title>"
+ "<Description><![CDATA[%5$s]]></Description>" + "<MusicUrl><![CDATA[%6$s]]></MusicUrl>"
+ "<HQMusicUrl><![CDATA[%7$s]]></HQMusicUrl>" + "</Music>" + "<FuncFlag>0</FuncFlag>" + "</xml>";
/****** config 配置 start *******/
/******* config 配置 end ********/
public static final int MSG_TYPE_MRCP_CODE = 20001;// 每日菜谱
public static final String MSG_TYPE_MRCP_NAME = "每日菜谱";// 每日菜谱
public static final String MSG_TYPE_MRCP_SENDER = "定时发送";// 每日菜谱
/******* 中小学消息推送类型代码 start ********/
public static final int MSG_TYPE_QXTZ_CODE = 20003;// 全校通知
public static final String MSG_TYPE_QXTZ_NAME = "通知";// 全校通知
public static final int MSG_TYPE_BJTZ_CODE = 20004;// 班级通知
public static final String MSG_TYPE_BJTZ_NAME = "通知";// 班级通知
public static final int MSG_TYPE_TZ_TEACHER_CODE = 20005;// 老师通知
public static final String MSG_TYPE_TZ_TEACHER_NAME = "通知";// 老师通知
public static final int MSG_TYPE_MAIL_CODE = 20006;// 邮件提醒
public static final String MSG_TYPE_MAIL_NAME = "邮件提醒";// 邮件提醒
public static final int MSG_TYPE_OA_CODE = 20007;// OA办公
public static final String MSG_TYPE_OA_NAME = "OA办公";// OA办公
public static final int MSG_TYPE_XXT_CODE = 20008;// 校讯通
public static final String MSG_TYPE_XXT_NAME = "学校通知";// 校讯通
public static final int MSG_TYPE_REPLY_CODE = 20009;// 消息回复
public static final String MSG_TYPE_REPLY_NAME = "消息回复";// 消息回复
public static final int MSG_TYPE_XWGG_CODE = 20010;// 新闻公告
public static final String MSG_TYPE_XWGG_NAME = "新闻公告";// 新闻公告
public static final int MSG_TYPE_ZSKS_CODE = 20011;// 招生考试
public static final String MSG_TYPE_ZSKS_NAME = "招生考试";// 招生考试
public static final int MSG_TYPE_BJQ_CODE = 20012;// 班级圈
public static final String MSG_TYPE_BJQ_NAME = "班级圈";// 班级圈
public static final int MSG_TYPE_HDTZ_CODE = 20013;// 新闻公告
public static final String MSG_TYPE_HDTZ_NAME = "活动通知";// 新闻公告
public static final int MSG_TYPE_SENDIMAGE_CODE = 30001;// 发送照片
public static final String MSG_TYPE_SENDIMAGE_NAME = "精彩瞬间";// 发送照片
public static final int MSG_TYPE_HOMEWORK_CODE = 30002;// 作业提醒
public static final String MSG_TYPE_HOMEWORK_NAME = "作业提醒";// 学生作业通知
public static final int MSG_TYPE_SCORE_CODE = 30003;// 考试成绩通知
public static final String MSG_TYPE_SCORE_NAME = "成绩提醒";// 学生作业通知
public static final int MSG_TYPE_PAYMENT_CODE = 30004;// 缴费提醒
public static final String MSG_TYPE_PAYMENT_NAME = "缴费提醒";// 缴费提醒
public static final int MSG_TYPE_PAXY_BBQJ_CODE = 10005;// 宝宝请假
public static final String MSG_TYPE_PAXY_BBQJ_NAME = "请假申请";// 宝宝请假
/******* 中小学消息推送类型代码 end ********/
public static final int MSG_TYPE_PAXY_CODE = 10001;// 家长刷卡
public static final int MSG_TYPE_PAXY_PATRIARCH_CODE = 10001;// 家长刷卡
public static final int MSG_TYPE_PAXY_TEACHER_CODE = 10002;// 家长刷卡
public static final String MSG_TYPE_PAXY_PATRIARCH_NAME = "家长刷卡";// 老师刷卡
public static final String MSG_TYPE_PAXY_TEACHER_NAME = "老师刷卡";// 老师刷卡
public static final int MSG_TYPE_PATRIARCH_REPLY_CODE = 10004;// 家长回复
public static final String MSG_TYPE_PATRIARCH_REPLY_NAME = "家长回复";// 家长回复
public static final int MSG_TYPE_TEACHER_REPLY_CODE = 10007;// 家长老师回复
public static final String MSG_TYPE_TEACHER_REPLY_NAME = "老师回复";// 家长老师回复
public static final int MSG_TYPE_JYHD_LXLS_CODE = 10006;// 联系老师
public static final String MSG_TYPE_JYHD_LXLS_NAME = "家长来信";// 家长来信
// public static final int MSG_TYPE_UPLSIMG = 10006;
public static final int MSG_TYPE_CRM_NEWS_CODE = 40001;// 24小时图文消息
public static final String MSG_TYPE_CRM_NEWS_NAME = "CRM-NEWS";// 宝宝请假
public static final int MSG_TYPE_USER_GET_CODE = 50005; // 拉取关注用户数据
public static final int MSG_TYPE_USERINFO_GET_CODE = 50006; // 通过用户的微信加密id获取用户微信基本信息
/*** 系统参数 start ****/
/**
* 到校离校模版在config表中的代码
*/
public static final String TM00188_TEMPLATE = "TM00188";
/**
* 微信请假模版在config表中的代码
*/
// public static final String TM00222_TEMPLATE = "TM00222";
public static final String TM00190_TEMPLATE = "TM00190";
/**
* 微信作业模版在config表中的代码
*/
public static final String TM00376_TEMPLATE = "TM00376";
/**
* 微信考试成绩模版在config表中的代码
*/
public static final String TM00084_TEMPLATE = "TM00084";
/**
* 微信放假模版在config表中的代码
*/
public static final String TM00221_TEMPLATE = "TM00221";
/**
* 微信通用模版在config表中的代码——订阅成功模版
*/
public static final String TP_DYCG = "TM00157";
/**
* 微信通用模版在config表中的代码——教育行业-院校订阅成功模版
*/
public static final String TP_YX_DYCG = "OPENTM201387310";
/**
* 微信通用模版在config表中的代码——教育行业-院校学校通知模版
*/
public static final String OPENTM204845041_TEMPLATE = "OPENTM204845041";
/**
* 微信新闻公告通知模版在config表中的代码——教育行业-新闻公告通知模版
*/
public static final String OPENTM206848486_TEMPLATE = "OPENTM206848486";
/**
* 微信活动通知模版
*/
public static final String OPENTM207276768_TEMPLATE = "OPENTM207276768";
/**
* 微信支付通知模版
*/
public static final String OPENTM202841150_TEMPLATE = "OPENTM202841150";
/**
* 微信留言提醒模版
*/
public static final String OPENTM202309749_TEMPLATE = "OPENTM202309749";
/**
* 微信通用模版在config表中的代码——教育行业-老师私信提醒
*/
public static final String OPENTM207719517_TEMPLATE = "OPENTM207719517";
/**
* 微信通用模版在config表中的代码——教育行业-家长私信提醒
*/
public static final String OPENTM207719538_TEMPLATE = "OPENTM207719538";
/**
* 微信通用模版在config表中的代码——教育行业-工作提醒
*
* {{first.DATA}} 标题:{{keyword1.DATA}} 日期:{{keyword2.DATA}}
* 内容:{{keyword3.DATA}} {{remark.DATA}}
*/
public static final String OPENTM400885296_TEMPLATE = "OPENTM400885296";
/**
* 微信通用模版在config表中的代码——访客记录
*/
public static final String OPENTM411461864_TEMPLATE = "OPENTM411461864";
/**
* 学习任务反馈提醒
*/
public static final String OPENTM401105790_TEMPALE = "OPENTM401105790";
/**
* 微信用户绑定成功模版
*/
public static final String OPENTM202551326_TEMPLATE = "OPENTM202551326";
/**
* 微信用户绑定成功模版
*/
public static final String OPENTM400501478_TEMPLATE = "OPENTM400501478";
/**
* 审核模板
*/
public static final String OPENTM401266706_TEMPLATE = "OPENTM401266706";
/**
* 微信通用模版在config表中的域名
*/
public static final String DOMAIN_URL = "401";
/**
* 微信二维码服务地址
*/
public static final String WX_PROXY = "WX_PROXY";
/*** 系统参数 end ****/
/**
* 模拟发送文本
*/
public static final String MSG_PUSHTYPE_TEXT = "text";
/**
* 模拟发送图文消息,需先创建图文
*/
public static final String MSG_PUSHTYPE = "news";
/**
* 模拟发送图文消息
*/
public static final String MSG_PUSHTYPEL_MUSIC = "music";
public static final String NOTICE_NEWS_COVER = "http://qiniu.weixiaotong.com/wxt_twtz.jpeg";
public static final String MRCP_NEWS_COVER = "http://static.weixiaotong.com.cn/c3daa812e3a160cb485360a8ff1eda2e95b32dce.jpg";
public static final String CHECK_SMS = "601";
public static final String WEBSTIE_INTERFACE_URL = "701";
/**
* 普通文本
*/
public static final int MSG_TYPE_TEXT_CODE = 90000;
/*************************** 业务功能 参数 *********************************/
/**
* 抽奖主题类型-用户绑定
*/
public static final String LOTTERY_TYPE_BINDING = "140001";
/**
* 首次绑定成功增加的有效抽奖次数
*/
public static final Integer LOTTERY_BINDING_CHANCE = 1;
/**
* 是否开启绑定后的抽奖功能
*/
public static final boolean IS_OPEN_BINDING_LOTTERY = false;
/**
* 消息通道为易信
*/
public static final int ORGCODE_YIXIN_CHANNEL = 1;
/**
* 关注人信息管理-绑定
*/
public static final int FAKEID_STATE_BINDING = 1;
/**
* 关注人信息管理-未绑定
*/
public static final int FAKEID_STATE_UNBINDING = 2;
/**
* 信息群发类型
*/
public static final int YQDT_TYPE_XXQF = 22;
/**
* 信息群发类型
*/
public static final String TYPE_RECEIVER_ALL = "0";
/**
* 信息群发类型
*/
public static final String TYPE_RECEIVER_BINDING = "1";
/**
* 信息群发类型
*/
public static final String TYPE_RECEIVER_UNBINDING = "2";
/**
* 班级圈类型
*/
public static final int WLZY_TYPE_BJQ = 5;
/**
* 宝宝作品
*/
public static final int WLZY_TYPE_BBZP = 6;
/**
* 成长记录 (微信 成长记录 图片保存)
*/
public static final int WLZY_TYPE_GROW = 7;
/**
* 微课
*/
public static final int WLZY_TYPE_WK = 10;
/**
* 宝宝作品条数
*/
public static final int WLZY_TYPE_BBZP_SIZE = 20;
/**
* 新闻公告1:推送
*/
public static final int WLZY_YQDT_PUSH = 1;
/**
* 主题活动:推送
*/
public static final int THEME_PUSH = 1;
/**
* 可见范围 1:公开
*/
public static final int WLZY_PHOTO_ISOPEN = 1;
/**
* 课堂动态类型:包括以前的(wlzy表中的:儿歌故事:1 ,经典音乐:2 ,经典游戏:3 ,微课堂:4,xxjj表中的:班级动态:4)
*/
public static final int WLZY_TYPE_KTDT = 1;
/**
* 未发布状态
*/
public static final int STATE_UN_PUBLISHED = 1;
/**
* 已发布状态
*/
public static final int STATE_PUBLISHED = 2;
/**
* 预约发布状态
*/
public static final int STATE_PRESET_PUBLISHED = 1;
/**
* 预览状态
*/
public static final int STATE_PREVIEW = 3;
/**
* 微信加密方式
*/
public static final String WECHAT_ENCRYPT_TYPE = "aes";
/**
* 微信token
*/
public static final String TOKEN = "yeywechat";
/**
* 微信端每页显示数据量
*/
public static final int PAGE_SIZE = 10;
/**
* 微信端每页显示数据量
*/
public static final int BIG_PAGE_SIZE = 20;
/**
* 信息已读状态
*/
public static final int INFO_IS_READ = 1;
/**
* 信息未读状态
*/
public static final int INFO_UN_READ = 0;
/**
* 信息已回复状态
*/
public static final int INFO_IS_REPLY = 1;
/**
* 图片类型:园所环境中上传的图片的类型
*/
public static final int FILE_TYPE_YSHJ = 98;
/**
* 图片类型:宝宝作品中上传的图片的类型
*/
public static final int FILE_TYPE_BBZP = 6;
/**
* 图片类型:主题活动中上传的图片的类型
*/
public static final int FILE_TYPE_ZTHD = 120;
/**
* 公用模板的orgcode
*/
public static final Long COMMON_TEMPLATE_ORGCODE = 1000L;
/**
* 公用模板的campusid
*/
public static final Long COMMON_TEMPLATE_CAMPUSID = 0L;
/**
* 中科院学校编码10010
*/
public static final Long ORG_ORGCODE_ZKY = 10010L;
/**
* 小博士幼儿园学校编码10018
*/
public static final Long ORG_ORGCODE_XBS = 10018L;
/**
* 总部公众帐号编码10008 幼儿园
*/
public static final Long ORG_ORGCODE_MAIN = 10008L;
/**
* 总部公众帐号编码10136 中小学
*/
public static final Long ORG_ORGCODE_SCHOOL_MAIN = 10136L;
/**
* 总部公众帐号编码10172 培训机构 课堂外
*/
public static final Long ORG_ORGCODE_TRAIN_MAIN = 10172L;
/**
* 取消点赞-返回页面的参数
*/
public static final String PRAISE_RETURN_CANCEL = "cancel";
/**
* 点赞-返回页面的参数
*/
public static final String PRAISE_RETURN_SUCCESS = "success";
/**
* 类型:通知类型 全校通知
*/
public static final int TZ_TYPE_1 = 1;
/**
* 类型:通知类型 班级通知
*/
public static final int TZ_TYPE_2 = 2;
/**
* 类型:通知类型 老师通知
*/
public static final int TZ_TYPE_4 = 4;
/**
* 类型:通知类型 联系老师
*/
public static final int TZ_TYPE_5 = 5;
/**
* 类型:通知类型 请假
*/
public static final int TZ_TYPE_6 = 6;
/**
* 类型:通知类型 家长和家长联系
*/
public static final int TZ_TYPE_7 = 7;
/**
* 类型:园长信箱
*/
public static final int TZ_TYPE_8 = 8;
/**
* 主题活动-主要信息的分类参数
*/
public static final String ACTIVITY_TYPE_INFO = "mainInfo";
/**
* 主题活动-照片墙的分类参数
*/
public static final String ACTIVITY_TYPE_PHOTO = "photoWall";
/**
* 在线资源-类型-儿歌
*/
public static final int RESOURCE_TYPE_EG = 1;
/**
* 在线资源-类型-儿童小说
*/
public static final int RESOURCE_TYPE_ETXS = 2;
/**
* 在线资源-类型-启蒙
*/
public static final int RESOURCE_TYPE_QM = 3;
/**
* 在线资源-类型-国学
*/
public static final int RESOURCE_TYPE_GX = 4;
/**
* 在线资源-类型-故事
*/
public static final int RESOURCE_TYPE_GS = 5;
/**
* 在线资源-类型-英语
*/
public static final int RESOURCE_TYPE_YY = 6;
/**
* 在线资源-类型-评书
*/
public static final int RESOURCE_TYPE_PS = 7;
/**
* 在线资源-资格格式
*/
public static final String RESOURCE_FORMAT_AUDIO = "mp3";
/**
* 班级主题活动-保存图片时的类型
*/
public static final int FILE_TYPE_THEME = 120;
/**
* 班级是否毕业-未毕业:0
*/
public static final int BJSJ_ISNOT_BYBJ = 0;
/**
* 班级是否毕业-未毕业:0
*/
public static final int NJSJ_ISNOT_BYNJ = 0;
/**
* 发送消息-学生通知
*/
public static final int SENDMSG_TYPE_XSTZ = 1;
/**
* 发送消息-老师通知
*/
public static final int SENDMSG_TYPE_LSTZ = 2;
/**
* 发送消息-请假
*/
public static final int SENDMSG_TYPE_QJ = 3;
/**
* 发送消息-联系老师
*/
public static final int SENDMSG_TYPE_LXLS = 4;
/**
* 发送消息-联系学生(家长间联系)--add by yjf
*/
public static final int SENDMSG_TYPE_LXXS = 5;
/**
* 系统-安卓
*/
public static final String SYSTEM_TYPE_ANDROID = "android";
/**
* 系统-苹果
*/
public static final String SYSTEM_TYPE_IOS = "ios";
/**
* 系统-移动端
*/
public static final String SYSTEM_TYPE_MOBILE = "mobile";
/**
* 系统-PC端
*/
public static final String SYSTEM_TYPE_PC = "pc";
// 数据来源-幼儿园
public final static String SOURCE_YEY = "YEY";
// 数据来源-管理平台
public final static String SOURCE_ZXX = "ZXX";
// 数据来源-网站
public final static String SOURCE_WZ = "WZ";
/**
* 活动关键字
*/
public final static String ORG_HD_KEYWORD = "光海萌宝宝";
/**
* 默认开始页
*/
public final static int WLZY_DEFAULT_PAGE = 1;
/**
* 老师配卡数据模版SHEET名称
*/
public final static String CARD_TEMPLATE_SHEETNAME_TEACHER = "老师配卡数据模版";
/**
* 老师配卡数据模版SHEET名称
*/
public final static int CARD_TEMPLATE_TYPE_TEACHER = 1;
/**
* 学生配卡数据模版SHEET名称
*/
public final static String CARD_TEMPLATE_SHEETNAME_STU = "学生配卡数据模版";
/**
* 学生配卡数据模版SHEET名称
*/
public final static int CARD_TEMPLATE_TYPE_STU = 2;
public static final String USERINFO_URL_WECHAT = "https://api.weixin.qq.com/cgi-bin/user/info?lang=zh_CN&";
public static final String USERINFO_URL_YIXIN = "https://api.yixin.im/cgi-bin/user/info?";
public static final String USERLIST_URL_WECHAT = "https://api.weixin.qq.com/cgi-bin/user/get?";
public static final String USERLIST_URL_YIXIN = " https://api.yixin.im/sns/oauth2/access_token?grant_type=authorization_code&";
/**
* 增加模版,获取template_id
*/
public static final String WECHAT_ADDTEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?";
/**
* 食谱发送时间configcode
*/
public static final String MRCP_SENDTIME_CONFIGCODE = "201";
/**
* sha1加密次数
*/
public static final int HASH_INTERATIONS = 1024;
/**
* 初始密码
*/
public static final String DEFAULT_PASSWORD = "123456";
/**
* 在线报名录取后,学生的默认班级id
*/
public static final long ZXBM_DEFAULT_BJID = -1;
/**
* 操作状态:0:新增,1:修改,-1需要删除
*/
public static final Integer SET_CARD_TYPE_ADD = 0;
public static final Integer SET_CARD_TYPE_UPDATE = 1;
public static final Integer SET_CARD_TYPE_DELETE = -1;
/**
* 删除用户操作的APPID标识,记录日志用
*/
public static final String LOG_APPID_DELETE_USER = "1703";
/**
* 学校服务默认免费结束日期
*/
public static final String XX_SERVICE_FREE_END_RQ = "2030-01-01";
/**
* 学校服务默认开始日期
*/
public static final String XX_SERVICE_START_RQ = "2030-01-02";
/**
* 学校服务默认结束日期
*/
public static final String XX_SERVICE_END_RQ = "2030-01-02";
/**
* 学校管理审核状态-审核中
*/
public static final int XX_AUDIT_STATE_ING = 1;
/**
* 学校管理审核状态-审核通过
*/
public static final int XX_AUDIT_STATE_PASS = 2;
/**
* 学校管理审核状态-审核未通过
*/
public static final int XX_AUDIT_STATE_NOPASS = -1;
/**
* 服务开通状态
*/
public static final int PAY_STATE_OPENSERVICE = 1;
/**
* 服务开通状态-未出账
*/
public static final int PAY_SERVICEPOINT_NOACCOUNT = 1;
/**
* 服务开通-线下支付
*/
public static final int PAY_TYPE_FORMAM = 1;
/**
* 服务开通-线上支付
*/
public static final int PAY_TYPE_FORWEIXIN = 2;
/**
* 微信端-没有校区时设置默认校区ID为0
*/
public static final String CAMPUSID_DEFAULT_VALUE = "0";
/**
* 微信端-班级圈类型:1 (公开)班级圈;2:(私密)个人相册
*/
public static final int BJQ_TYPE_ISOPEN = 1;
/**
* 班级管理-是否为毕业班级 0:否;1:是
*/
public static final int BJSJ_NOT_BYBJ = 0;
/**
* 异步请求返回值 标识请求操作成功
*/
public static final String AJAX_REQUEST_SIGN_SUCCESS = "200";
/**
* 异步请求返回值 标识请求操作失败
*/
public static final String AJAX_REQUEST_SIGN_FAIL = "400";
/**
* 异步请求返回值 -打赏-余额不足
*/
public static final String AJAX_REQUEST_SIGN_REWARD_NOMONEY = "500";
/**
* 周一
*/
public static final Integer WEEKDAY_NUM_MONDAY = 1;
/**
* 周日
*/
public static final Integer WEEKDAY_NUM_SUNDAY = 7;
/**
* 阅读-考试-问题类型
*/
public static final String DICT_TYPE_READ_EXAM_QUESTION_TYPE = "QUESTION_TYPE";
/**
* 收费管理-缴费类型-幼儿园
*/
public static final String DICT_TYPE_PAYMENT_TYPE_PARK = "PAYTYPE_PARK";
/**
* 收费管理-缴费类型-中小学
*/
public static final String DICT_TYPE_PAYMENT_TYPE_SCHOOL = "PAYTYPE_SCHOOL";
/**
* 数据字典-OA控件类型
*/
public static final String DICT_TYPE_OA_CONTROLS_TYPE = "OACONTROLS";
/**
* 数据字典-奖项字典类型
*/
public static final String DICT_TYPE_GHHD_AWARD_TYPE = "AWARDTYPE";
/**
* 数据字典-投票规则字典类型
*/
public static final String DICT_TYPE_GHHD_VOTE_RULE = "VOTERULE";
/**
* 数据字典-活动类型
*/
public static final String DICT_TYPE_GHHD_ACTIVITY_TYPE = "ACTIVITYTYPE";
/**
* 数据字典-家长关系对应
*/
public static final String DICT_TYPE_PARENT_RELATIONS = "XSJZ";
/**
* 数据字典-家长学历对应
*/
public static final String DICT_TYPE_EDUCATIONAL_BACKGROUND = "XLTYPE";
/**
* 数据字典-微信端各模块在首页显示的记录数
*/
public static final String DICT_TYPE_ARTICLE_DATALIMIT = "DATALIMIT";
/**
* 数据字典-反馈类型
*/
public static final String DICT_TYPE_ADVISE_TYPE = "FKLX";// 反馈类型
/**
* 数据字典-血型
*/
public static final String DICT_TYPE_BLOODTYPE = "BLOODTYPE";
/**
* 数据字典-性别
*/
public static final String DICT_TYPE_SEX = "SEX";
/**
* 数据字典-绑定状态
*/
public static final String DICT_TYPE_BIND = "BIND";
/**
* 数据字典-是否
*/
public static final String DICT_TYPE_WHETHER = "WHETHER";
/**
* 数据字典-请假类型
*/
public static final String DICT_TYPE_QJLX = "QJLX";
/**
* 数据字典-评语
*/
public static final String DICT_TYPE_COMMENT = "COMMENT";
/**
* 打卡查询-全部
*/
public static final String PUNCHCARD_TYPE_ALL = "ALL";
/**
* 打卡查询-未打卡
*/
public static final String PUNCHCARD_TYPE_NOTPUNCH = "NOTPUNCH";
/**
* 数据字典-民族对应
*/
public static final String DICT_TYPE_MZLX = "MZLX";
/**
* 数据字典-婚姻状况对应
*/
public static final String DICT_TYPE_MARITAL = "MARITAL";
/**
* 数据字典-政治面貌对应
*/
public static final String DICT_TYPE_POLITICAL = "POLITICAL";
/**
* 数据字典-考勤机类型
*/
public static final String DICT_TYPE_MECHINE_TYPE = "MECHINE_TYPE";
/**
* 数据字典-考勤机状态
*/
public static final String DICT_TYPE_MECHINE_STATE = "MECHINE_STATE";
/**
* 数据字典-考勤机是否启用
*/
public static final String DICT_TYPE_MECHINE_ISOPEN = "MECHINE_ISOPEN";
/**
* 数据字典-考勤机是否启用
*/
public static final String DICT_TYPE_PUNCH_TYPE = "PUNCH_TYPE";
/**
* 数据字典-学校状态
*/
public static final String DICT_TYPE_SCHOOL_TYPE = "XXTYPE";
/**
* 数据字典-微信支付错误提示
*/
public static final String DICT_TYPE_PAY_ERROR_MSG = "PAYERRMSG";
/**
* 数据字典-城市.
*/
public static final String DICT_TYPE_CITY_TYPE = "CITY";
/**
* 数据字典-省份.
*/
public static final String DICT_TYPE_PROVINCE = "PROVINCE";
/**
* 数据字典-县区
*/
public static final String DICT_TYPE_COUNTYTOWN = "COUNTY_TOWN";
/**
* 数据字典-微信支付错误提示
*/
public static final String DICT_CODE_PAY_ERROR_MSG_01 = "PAYERRMSG_01";
/**
* 数据字典-考勤机状态
*/
public static final String DICT_TYPE_USE_TYPE = "USE_TYPE";
/**
* 数据字典-代理商广告:状态
*/
public static final String DICT_TYPE_DLS_AD_STATE = "DLS_AD_STATE";
/**
* 数据字典-聊天模式用户输入-游客反馈
*/
public static final String DICT_TYPE_WECHAT_PROMPT_VISITOR = "WECHAT_PROMPT_VISITOR";
/**
* 数据字典-聊天模式用户输入-游客反馈
*/
public static final String DICT_TYPE_DIFFICULTY_TYPE = "DIFFICULTY_TYPE";
/**
* 数据字典-聊天模式用户输入-园长反馈
*/
public static final String DICT_TYPE_WECHAT_PROMPT_LEADER = "WECHAT_PROMPT_LEADER";
/**
* 数据字典-聊天模式用户输入-管理员反馈
*/
public static final String DICT_TYPE_WECHAT_PROMPT_ADMIN = "WECHAT_PROMPT_ADMIN";
/**
* 数据字典-聊天模式用户输入-老师反馈
*/
public static final String DICT_TYPE_WECHAT_PROMPT_TEACHER = "WECHAT_PROMPT_TEACHER";
/**
* 数据字典-聊天模式用户输入-家长反馈
*/
public static final String DICT_TYPE_WECHAT_PROMPT_PATRIARCH = "WECHAT_PROMPT_PATRIARCH";
/**
* 数据字典-微信认证状态
*/
public static final String DICT_WECHAT_VERIFYSTATE = "WECHAT_VERIFYSTATE";
/**
* 消息推送类型
*/
public static final String DICT_TYPE_MSGTYPE = "MSGTYPE";
/**
* 学段类型
*/
public static final String DICT_TYPE_PERIOD = "PERIOD_TYPE";
/**
* 题型 QUESTION_TYPE_ + courseType
*/
public static final String DICT_TYPE_QUESTION_TYPE = "QUESTION_TYPE_";
/**
* 考勤
*/
public static final int MESSAGE_TYPE_ATTENDANCE_FOR_APP = 8;
/**
* 请假
*/
public static final int MESSAGE_TYPE_LEAVE_FOR_APP = 6;
/**
* 食谱
*/
public static final int MESSAGE_TYPE_RECIPE_FOR_APP = 5;
/**
* 消息
*/
public static final int MESSAGE_TYPE_COMMON_FOR_APP = 4;
/**
* 新闻
*/
public static final int MESSAGE_TYPE_NEWS_FOR_APP = 3;
/**
* 公告
*/
public static final int MESSAGE_TYPE_ANNOUNCEMENT_FOR_APP = 2;
/**
* 资讯
*/
public static final int MESSAGE_TYPE_INFORMATION_FOR_APP = 7;
/**
* 系统消息
*/
public static final int MESSAGE_TYPE_SYSTEM_FOR_APP = 33;
/**
* 通讯录-老师TAB
*/
public static final String ADDRESSBOOK_TYPE_TEACHER_FOR_APP = "0";
/**
* 通讯录-学生分组TAB
*/
public static final String ADDRESSBOOK_TYPE_STUGROUP_FOR_APP = "1";
/**
* 通讯录-班级TAB
*/
public static final String ADDRESSBOOK_TYPE_CLASS_FOR_APP = "2";
// 用户请求 微校通app请求
public static final String USER_AGENT_WXT = "WeiXiaoTong";
public static Boolean checkUserAgent(String userAgent) {
if (USER_AGENT_WXT.equals(userAgent)) {
return true;
} else {
return false;
}
}
public static String PAY_UNIFIEDORDER_URI = "/pay/unifiedorder";
public static String getPayUnifiedorderUri(String source) {
return "/" + source + PAY_UNIFIEDORDER_URI;
}
/**
* app消息推送类型-通知
*/
public static final String MESSAGE = "message";
/**
* app消息推送类型-通知回复
*/
public static final String MESSAGE_REPLY = "msgreply";
/**
* app消息推送类型-班级圈
*/
public static final String CLASSCIRCLE = "classcircle";
public static final String CLASSCIRCLE_COMMENT = "newcomment";
/**
* app消息推送类型-成长
*/
public static final String GROW = "grow";
/**
* app消息推送类型-透传数据
*/
public static final String SYSTEM_DATA = "msgdata";
/**
* app消息透传类型-确认时推送消息给发送人
*/
public static final String DT_UPDATE_CONFIRM_FOR_SENDER = "1";
/**
* app消息透传类型-回复时推送消息给发送人
*/
public static final String DT_UPDATE_REPLY_FOR_SENDER = "2";
/**
* app消息透传类型-同步消息确认数量到APP
*/
public static final String DT_SYNCHRONOUS_CONFIRM_FOR_RECEIVER = "3";
/**
* app消息透传类型-同步消息回复数量到APP
*/
public static final String DT_SYNCHRONOUS_REPLY_FOR_RECEIVER = "4";
/**
* 在MemCacheForOneCardUtil里的key里可以批量删除
*/
public static final String MEMCACHE_FOR_ONE_CARD_UTIL_SINGE_AND_BATCH = "MEMCACHEFORONECARDUTIL_SINGE_AND_BATCH";
/**
* 在MemCacheForOneCardUtil里的不能批量删除
*/
public static final String MEMCACHE_FOR_ONE_CARD_UTIL_SINGE = "MEMCACHEFORONECARDUTIL_SINGE";
/**
* 在MemCacheUtil里的key里可以批量删除
*/
public static final String MEMCACHE_UTIL_SINGE_AND_BATCH = "MEMCACHEUTIL_SINGE_AND_BATCH";
/**
* 在MemCacheUtil里的不能批量删除
*/
public static final String MEMCACHE_UTIL_SINGE = "MEMCACHEUTIL_SINGE";
/**
* 属相.
*/
public static final String DICT_TYPE_ZODIAC = "ZODIAC";
/**
* 星座.
*/
public static final String DICT_TYPE_CONSTELLATION = "CONSTELLATION";
public static final int IDISPLAY_START = 0;
public static final int IDISPLAY_LENGTH = 9999999;
/**
* 课程类型
*/
public static final String DICT_TYPE_COURSETYPE = "COURSETYPE";
/**
* 活动详情列表每页个数
*/
public static final int ACTIVITY_DETAILS_PAGINAL_SIZE = 6;
/**
* 社教广场菜单类型
*/
public static final int MENU_TYPE_SJGC = 0;
/**
* EXKJ菜单类型
*/
public static final int MENU_TYPE_EXKJ = 1;
/**
* 上城区街道类型
*/
public static final String DICT_TYPE_STREET_TYPE = "SCSTREETTYPE";
/**
* 课程数据已发布状态
*/
public static final Long KCSJ_STATE_1 = 1L;
public static final int WXPAY_BUSINESS_CODE_APPLY = 1; // 社区学院报名
public static final int WXPAY_BUSINESS_CODE_SMARTCARD = 4;// 一卡通充值
/**
* 二维码类型:临时
*/
public static final String ACTION_NAME_QR_SCENE = "QR_SCENE";
/**
* 二维码类型:永久
*/
public static final String ACTION_NAME_QR_LIMIT_SCENE = "QR_LIMIT_STR_SCENE";
public static final int QR_EXPIRE_SECONDS = 2592000;// 30天,腾讯默认最多30天
/**
* 已关注微信公众号
*/
public static final int SUBSCRIBE = 1;
/**
* 未关注微信公众号
*/
public static final int UNSUBSCRIBE = 0;
/**
* 班级职位.
*/
public static final String DICT_TYPE_CLASS_COMMITTEE = "CLASS_COMMITTEE";
public static final Long SENDER_ID_SYSTEM = -1L;
public static final String SENDER_NAME_SYSTEM = "光海萌宝宝";
public static final String STU_NOT_EXIST_DISPLAY = "该学生不存在!";
/**
* 外部接口地址
*/
public final static String WX_COMPONENT_POST_URL = "https://api.weixin.qq.com/cgi-bin/component/";// 微信开放平台接口调用前缀地址
/**
* 微信端-请求页面路径
*/
public final static String commonUrl_wechatOauth2RedirectUri = "/mobile/wechatOauth2/";
public static String getWechatOauth2RedirectUri() {
return commonUrl_wechatOauth2RedirectUri;
}
public final static String APPID_VUE_PAGE = "888888";// 非公开页面
public final static String APPID_VUE_PAGE_OPEN = "888889";// 公开页面
public final static String APPID_VUE2_PAGE_OPEN = "888891";
public static final String INSERT = "INSERT";
public static final String UPDATE = "UPDATE";
public static final String DELETE = "DELETE";
public static final String NONE = "NONE";
public static final String CAMERA_TYPE_NVR = "NVR";
public static final String CAMERA_TYPE_SIX_SECONDS = "SIXSECONDS";
public static final String SMS = "SMS";
}
package com.spacetech.common.entity;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
/**
* 统一定义id的entity基类.
*
* 基类统一定义id的属性名称、数据类型、列名映射及生成策略.
* Oracle需要每个Entity独立定义id的SEQUCENCE时,不继承于本类而改为实现一个Idable的接口。
*
* @author calvin
*/
// JPA 基类的标识
@MappedSuperclass
public abstract class IdEntity {
protected String id;
@Id
@Column(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
package com.spacetech.common.entity;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
/**
* 统一定义id的entity基类.
*
* 基类统一定义id的属性名称、数据类型、列名映射及生成策略.
* Oracle需要每个Entity独立定义id的SEQUCENCE时,不继承于本类而改为实现一个Idable的接口。
*
* @author calvin
*/
// JPA 基类的标识
@MappedSuperclass
public abstract class IdLongEntity{
protected Long id;
@Id
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
package com.spacetech.common.exception;
public class ApiException extends RuntimeException {
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public Throwable getErrorCause() {
return errorCause;
}
public void setErrorCause(Throwable errorCause) {
this.errorCause = errorCause;
}
private static final long serialVersionUID = -9171287832448832971L;
protected String errorMsg; // 错误信息(For debug)
protected Throwable errorCause = null; // 错误发生原因(原始Exception)
public ApiException(Throwable e, String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
this.errorCause = e;
}
public ApiException(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
}
package com.spacetech.common.exception;
/**
* 异常处理基类
*
* @author wm
*
*/
public class BaseException extends RuntimeException {
private static final long serialVersionUID = -5154615570448990996L;
protected String errorCode; // 错误代码(属性表文件中定义其message)
protected String errorMsg; // 错误信息(For debug)
protected Object[] parameters; // 参数列表(错误代码对应的message需要的参数列表)
protected Throwable errorCause; // 错误发生原因(原始Exception)
protected String errorDetail; // 错误详细信息
/**
* Constructor
*
* @param errorMsg
* @param errorCode
* @param parameters
* @param e
*/
public BaseException(String errorMsg, String errorDetail, String errorCode,
Object[] parameters) {
super(errorMsg);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
this.errorDetail = errorDetail;
this.parameters = parameters;
}
/**
* Constructor
*
* @param errorMsg
* @param errorCode
* @param parameters
* @param e
*/
public BaseException(String errorMsg, String errorDetail, String errorCode,
Object[] parameters, Throwable e) {
super(errorMsg, e);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
this.errorDetail = errorDetail;
this.errorCause = e;
this.parameters = parameters;
}
public Throwable getErrorCause() {
return errorCause;
}
public void setErrorCause(Throwable errorCause) {
this.errorCause = errorCause;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public Object[] getParameters() {
return parameters;
}
public void setParameters(String[] parameters) {
this.parameters = parameters;
}
public String getErrorDetail() {
return errorDetail;
}
public void setErrorDetail(String errorDetail) {
this.errorDetail = errorDetail;
}
}
package com.spacetech.common.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 业务处理异常类
*
* @author wm
*
*/
public class BusinessException extends BaseException {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory
.getLogger(BusinessException.class);
/**
* Constructor
*
* @param errorCode
*/
public BusinessException(String errorMsg) {
super(errorMsg, null, null, null);
}
/**
* Constructor
*
* @param errorCode
* @param parameters
*/
public BusinessException(String errorCode, Object[] parameters) {
super(null, null, errorCode, parameters);
}
/**
* Constructor
*
* @param errorCode
* @param e
*/
public BusinessException(String errorMsg, Throwable e) {
super(errorMsg, null, null, null, e);
}
/**
* Constructor
*
* @param errorCode
* @param parameters
* @param e
*/
public BusinessException(String errorCode, Object[] parameters, Throwable e) {
super(null, null, errorCode, parameters, e);
}
/**
* Constructor
*
* @param errorMsg
* @param errorCode
*/
public BusinessException(String errorMsg, String errorCode) {
super(errorMsg, null, errorCode, null);
}
/**
* Constructor
*
* @param errorMsg
* @param errorCode
* @param parameters
*/
public BusinessException(String errorMsg, String errorCode,
Object[] parameters) {
super(errorMsg, null, errorCode, parameters);
}
/**
* Constructor
*
* @param errorMsg
* @param errorCode
* @param parameters
* @param e
*/
public BusinessException(String errorMsg, String errorCode,
Object[] parameters, Throwable e) {
super(errorMsg, null, errorCode, parameters, e);
}
/**
* Constructor
*
* @param errorMsg
* @param errorDetail
* @param errorCode
*/
public BusinessException(String errorMsg, String errorDetail,
String errorCode) {
super(errorMsg, errorDetail, errorCode, null);
}
/**
* Constructor
*
* @param errorMsg
* @param errorDetail
* @param errorCode
* @param e
*/
public BusinessException(String errorMsg, String errorDetail,
String errorCode, Throwable e) {
super(errorMsg, errorDetail, errorCode, null, e);
}
/**
* Constructor
*
* @param errorMsg
* @param errorDetail
* @param errorCode
* @param parameters
*/
public BusinessException(String errorMsg, String errorDetail,
String errorCode, Object[] parameters) {
super(errorMsg, errorDetail, errorCode, parameters, null);
}
/**
* Constructor
*
* @param errorMsg
* @param errorDetail
* @param errorCode
* @param parameters
* @param e
*/
public BusinessException(String errorMsg, String errorDetail,
String errorCode, Object[] parameters, Throwable e) {
super(errorMsg, errorDetail, errorCode, parameters, e);
}
}
package com.spacetech.common.exception;
import java.io.Serializable;
public class ExcelDataCheckException extends RuntimeException implements
Serializable {
private static final long serialVersionUID = 1L;
public ExcelDataCheckException(String errorMsg) {
super(errorMsg);
}
}
package com.spacetech.common.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.spacetech.common.utils.StringUtil;
public class ExceptionUtil {
private static Logger logger = LoggerFactory.getLogger(ExceptionUtil.class);
public boolean extractApiException(java.lang.reflect.InvocationTargetException e) {
String className = e.getTargetException().getClass().getName();
// if(){
//
// }
return false;
}
public static String transformDbException(String msg) {
if (StringUtil.isNullOrEmpty(msg)) {
return "";
}
if (msg.indexOf("exception.SQL") > -1 || msg.indexOf("JDBCException") > -1
|| msg.indexOf("NonUniqueResultException") > -1 || msg.indexOf("QueryException") > -1
|| msg.indexOf("org.hibernate") > -1 || msg.indexOf("InvocationTargetException") > -1) {
return "系统发生错误,请联系管理员稍后重试!";
}
if (msg.indexOf("Forbid consumer") > -1 || msg.indexOf("No provider available") > -1) {
return "平台访问量过大,请稍后重试";
}
return msg;
}
}
package com.spacetech.common.exception;
public class FilePutErrorException extends BusinessException {
public FilePutErrorException(String errorCode) {
super(errorCode);
// TODO Auto-generated constructor stub
}
/**
*
*/
private static final long serialVersionUID = 112311234123423452L;
}
package com.spacetech.common.logger;
import org.apache.log4j.MDC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.spacetech.common.utils.StringUtil;
public class LoggerUtil {
private static Logger logger = LoggerFactory.getLogger(LoggerUtil.class);
public static String setMdcRequestId(String requestId) {
if (StringUtil.isNullOrEmpty(requestId)) {
requestId = StringUtil.getIdGenerator();
}
MDC.put("requestId", requestId);
return requestId;
}
}
package com.spacetech.common.utils;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.spacetech.common.ConstantVar;
import com.spacetech.common.utils.wechat.AesException;
import com.spacetech.common.utils.wechat.WXBizMsgCrypt;
import com.spacetech.common.utils.wechat.XmlIterator;
import sun.misc.BASE64Encoder;
public class AESUtil {
public static final String AES_KEY = "J90a*&j_~!ks^T4j";
private static final String AES = "AES";
private static Logger logger = LoggerFactory.getLogger(AESUtil.class);
public static String AES_KEY_DATA_SAFE = "J90a*&j_~!ks^T4j";
/**
* 加密
*
* @param encryptStr
* @return
*/
private static byte[] encrypt(byte[] src, String key) throws Exception {
Cipher cipher = Cipher.getInstance(AES);
SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), AES);
cipher.init(Cipher.ENCRYPT_MODE, securekey);// 设置密钥和加密形式
return cipher.doFinal(src);
}
/**
* 解密
*
* @param decryptStr
* @return
* @throws Exception
*/
private static byte[] decrypt(byte[] src, String key) throws Exception {
Cipher cipher = Cipher.getInstance(AES);
SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), AES);// 设置加密Key
cipher.init(Cipher.DECRYPT_MODE, securekey);// 设置密钥和解密形式
return cipher.doFinal(src);
}
/**
* 二行制转十六进制字符串
*
* @param b
* @return
*/
private static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase();
}
public static byte[] hex2byte(byte[] b) {
if ((b.length % 2) != 0)
throw new IllegalArgumentException("长度不是偶数");
byte[] b2 = new byte[b.length / 2];
for (int n = 0; n < b.length; n += 2) {
String item = new String(b, n, 2);
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
}
/**
* 系统重要业务数据解密.
*
* @param data
* @return
*/
public final static String decryptForDataSafe(String data, String key) {
return decrypt(data, key);
}
/**
* 系统重要业务数据解密,有长度限制.
*
* @param data
* @return
*/
public final static String decryptLimitForDataSafe(String data, int datalength) {
return decryptLimit(data, AES_KEY_DATA_SAFE, datalength);
}
/**
* 系统重要业务数据加密.
*
* @return
* @throws Exception
*/
public final static String encryptForDataSafe(String data, String key) {
return encrypt(data, key);
}
/**
* 系统重要业务数据加密,限制长度.
*
* @return
* @throws Exception
*/
public final static String encryptLimitForDataSafe(String data, int datalength) {
return encryptLimit(data, AES_KEY_DATA_SAFE, datalength);
}
/**
* 解密
*
* @param data
* @return
* @throws Exception
*/
public final static String decrypt(String data, String key) {
if (StringUtil.isNullOrEmpty(data) || data.length() < 16) {
return data;
}
try {
return new String(decrypt(hex2byte(data.getBytes()), key));
} catch (Exception e) {
logger.warn("数据解密失败:data=" + data + " key=" + key + " 错误原因:" + e.getMessage());
return data;
}
}
public final static String decryptLimit(String data, String key, int datalength) {
try {
if (StringUtil.isNotEmpty(data) && data.length() > datalength) {
return new String(decrypt(hex2byte(data.getBytes()), key));
} else {
return data;
}
} catch (Exception e) {
logger.warn(
"数据解密失败:data=" + data + " key=" + key + " datalength=" + datalength + " 错误原因:" + e.getMessage());
return data;
}
}
/**
* 加密
*
* @param data
* @return
* @throws Exception
*/
public final static String encrypt(String data, String key) {
if (StringUtil.isNullOrEmpty(data)) {
return "";
}
try {
return byte2hex(encrypt(data.getBytes(), key));
} catch (Exception e) {
logger.warn("数据加密失败:data=" + data + " key=" + key + " 错误原因:" + e.getMessage());
return data;
}
}
public final static String encryptLimit(String data, String key, int datalength) {
try {
if (StringUtil.isNotEmpty(data) && data.length() < datalength) {
return byte2hex(encrypt(data.getBytes(), key));
} else {
return data;
}
} catch (Exception e) {
logger.warn(
"数据加密失败:data=" + data + " key=" + key + " datalength=" + datalength + " 错误原因:" + e.getMessage());
return data;
}
}
public final static String encryptWechat(String data, String encodingAesKey, String appId) throws AesException {
SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yymmddhhmm");
String timestamp = sdfDateFormat.format(new Date());
WXBizMsgCrypt pc = new WXBizMsgCrypt(ConstantVar.TOKEN, encodingAesKey, appId);
String result = pc.encryptMsg(data, timestamp, ConstantVar.AES_KEY);
// System.out.println("encryptWechat result="+result);
return result;
}
public final static String decryptWechat(String data, String encodingAesKey, String appId, String msg_signature,
String timestamp, String nonce, String key) throws AesException {
Map<String, String> map = XmlIterator.interatorXML(data);
WXBizMsgCrypt pc = new WXBizMsgCrypt(ConstantVar.TOKEN, encodingAesKey, appId);
String encrypt = map.get("Encrypt");
String toUser = map.get(key);
String format = "<xml><" + key + "><![CDATA[%1$s]]></" + key + "><Encrypt><![CDATA[%2$s]]></Encrypt></xml>";
String fromXML = String.format(format, toUser, encrypt);
//
// 公众平台发送消息给第三方,第三方处理
//
// 第三方收到公众号平台发送的消息
String result = pc.decryptMsg(msg_signature, timestamp, nonce, fromXML);
return result;
}
public static void main(String[] paramArrayOfString) throws Exception {
String a = AESUtil.encryptForDataSafe("3fb6c04eaa3c761e9611a50975228021", "");
System.out.println(a);
String data = "W1koX4Bd6C4/m9QAJ8qyNBBlbIN5Sc611yostscnDRXePWXIbKuxOA74KijquKmK3z3VVM98LHjzVeSA6JyL2YJDNLYigzdKqAWDco2fNeXUZ4X0bohV8lf0gWQtN60xaUrkCyfIBFA8QoC9cw6fK4jEqutYaSZdQMIG7lsbwyAWn3nWZQHg0J8CLk6ILvb3ffRUZO1rfiVwjl9rpU8PVQB90YLBrL6sC4INxNAgRMh7CoCU2NGrdXQCxwe3TefSPxWtX6GmToZw61xhZFhwp2YiKBpXZkLVN/ChpA7H4nGXvj8OG3XRC7FRJjRsP6J9PBQNob7kuISl9f4lOeqRhZVkaGFaI55Pv8TFvqCRexKT1VDfU06cN0wMVBOUrgzOVccP5lBglcC4OZGGkMbJRKznlPIlUbpYrebgLiyi3ag=";
String encodingAesKey = "7vpPNkH02ojRulepw0yyQ2O5TvqwpL2cRXFsSO9Vf14";
String appId = "wxc0b82c673bfaadf9";
String msg_signature = "854703afddd36ea0c0542f3a50af8dd1c3467d59";
String timestamp = "1472181934";
String nonce = "2029305636";
String key = "ToUserName";
decryptWechat(data, encodingAesKey, appId, msg_signature, timestamp, nonce, key);
}
/**
* 系统重要业务数据解密.
*
* @param data
* @return
*/
public final static String decryptForDataSafe(String data) {
return decrypt(data, AES_KEY_DATA_SAFE);
}
/**
* 系统普通数据加密
*
* @param data
* @return
*/
public final static String encrypt(String data) {
return encrypt(data, AES_KEY);
}
/**
* 系统普通数据解密
*
* @param data
* @return
*/
public final static String decrypt(String data) {
return decrypt(data, AES_KEY);
}
/**
* 加密
*
* @param content
* @param encodeRules
* @return
*/
public static String AESEncrypt(String content, String encodeRules) {
try {
// 1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator keygen = KeyGenerator.getInstance(AES);
// 2.根据ecnodeRules规则初始化密钥生成器
// 生成一个128位的随机源,根据传入的字节数组
keygen.init(128, new SecureRandom(encodeRules.getBytes()));
// 3.产生原始对称密钥
SecretKey original_key = keygen.generateKey();
// 4.获得原始对称密钥的字节数组
byte[] raw = original_key.getEncoded();
// 5.根据字节数组生成AES密钥
SecretKey key = new SecretKeySpec(raw, AES);
// 6.根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance(AES);
// 7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.ENCRYPT_MODE, key);
// 8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
byte[] byte_encode = content.getBytes("utf-8");
// 9.根据密码器的初始化方式--加密:将数据加密
byte[] byte_AES = cipher.doFinal(byte_encode);
// 10.将加密后的数据转换为字符串
String AES_encode = new String(new BASE64Encoder().encode(byte_AES));
// 11.将字符串返回
return AES_encode;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
package com.spacetech.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.spacetech.common.exception.ApiException;
import com.spacetech.common.exception.ExceptionUtil;
public class ApiUtil {
private static Logger logger = LoggerFactory.getLogger(ApiUtil.class);
public final static String SUCCESS = "200";
public final static String ERROR_INTERNAL_SERVER = "500";
public final static String ERROR_INTERNAL_SERVER_300 = "300";
public final static String ERROR_CLASS_NOTEXISTS = "001_001";
public final static String ERROR_METHOD_NOTEXISTS = "001_002";
public final static String MOCK_SERVER_URL = "http://localhost:8080/integtest/mockcall";
public static String formatJsonResult(String api, Object obj, String returnCode, String returnMsg, String version) {
JSONObject result = new JSONObject();
result.put("api", api);
result.put("data", obj);
result.put("v", version);
try {
result.put("ret", formatReturnMsg(returnCode, returnMsg));
return JSON.toJSONString(result, SerializerFeature.WriteMapNullValue,
SerializerFeature.DisableCircularReferenceDetect).replace(" ", " ");
} catch (Exception e) {
// TODO: handle exception
result = new JSONObject();
result.put("api", api);
result.put("v", version);
result.put("ret", formatReturnMsg(returnCode, "系统数据转换发生异常,请联系管理员"));
return JSON.toJSONString(result, SerializerFeature.WriteMapNullValue,
SerializerFeature.DisableCircularReferenceDetect).replace(" ", " ");
}
}
public static void verifyResponse(JSONObject resultJson) {
JSONObject ret = resultJson.getJSONObject("ret");
String code = ret.getString("code");
if (ERROR_INTERNAL_SERVER.equals(code)||ERROR_INTERNAL_SERVER_300.equals(code)) {
String msg = ret.getString("msg");
logger.error("systemerror msg" + JSONObject.toJSONString(resultJson));
throw new ApiException(ExceptionUtil.transformDbException(msg));
}
}
public static JSONObject formatReturnMsg(String code, String msg) {
JSONObject result = new JSONObject();
result.put("code", code);
if (ApiUtil.ERROR_INTERNAL_SERVER.equals(code)) {
msg = ExceptionUtil.transformDbException(msg);
}
result.put("msg", msg);
return result;
}
public static boolean isMockCall(JSONObject params) {
if (params == null) {
return false;
}
if (params.containsKey("mockcall")) {
return params.getBoolean("mockcall");
} else {
return false;
}
}
public static Class[] getJsonArgClass() throws ClassNotFoundException {
Class jsonClass = Class.forName("com.alibaba.fastjson.JSONObject");
Class[] argsClass = new Class[1];
argsClass[0] = jsonClass;
return argsClass;
}
}
package com.spacetech.common.utils;
import java.io.*;
public class Base64Decoder extends FilterInputStream {
private static final char[] chars = {
'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', '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 mapping between char values and six-bit integers
private static final int[] ints = new int[128];
static {
for (int i = 0; i < 64; i++) {
ints[chars[i]] = i;
}
}
private int charCount;
private int carryOver;
/***
* Constructs a new Base64 decoder that reads input from the given
* InputStream.
*
* @param in the input stream
*/
public Base64Decoder(InputStream in) {
super(in);
}
/***
* Returns the next decoded character from the stream, or -1 if
* end of stream was reached.
*
* @return the decoded character, or -1 if the end of the
* input stream is reached
* @exception IOException if an I/O error occurs
*/
public int read() throws IOException {
// Read the next non-whitespace character
int x;
do {
x = in.read();
if (x == -1) {
return -1;
}
} while (Character.isWhitespace((char)x));
charCount++;
// The '=' sign is just padding
if (x == '=') {
return -1; // effective end of stream
}
// Convert from raw form to 6-bit form
x = ints[x];
// Calculate which character we're decoding now
int mode = (charCount - 1) % 4;
// First char save all six bits, go for another
if (mode == 0) {
carryOver = x & 63;
return read();
}
// Second char use previous six bits and first two new bits,
// save last four bits
else if (mode == 1) {
int decoded = ((carryOver << 2) + (x >> 4)) & 255;
carryOver = x & 15;
return decoded;
}
// Third char use previous four bits and first four new bits,
// save last two bits
else if (mode == 2) {
int decoded = ((carryOver << 4) + (x >> 2)) & 255;
carryOver = x & 3;
return decoded;
}
// Fourth char use previous two bits and all six new bits
else if (mode == 3) {
int decoded = ((carryOver << 6) + x) & 255;
return decoded;
}
return -1; // can't actually reach this line
}
/***
* Reads decoded data into an array of bytes and returns the actual
* number of bytes read, or -1 if end of stream was reached.
*
* @param buf the buffer into which the data is read
* @param off the start offset of the data
* @param len the maximum number of bytes to read
* @return the actual number of bytes read, or -1 if the end of the
* input stream is reached
* @exception IOException if an I/O error occurs
*/
public int read(byte[] buf, int off, int len) throws IOException {
if (buf.length < (len + off - 1)) {
throw new IOException("The input buffer is too small: " + len +
" bytes requested starting at offset " + off + " while the buffer " +
" is only " + buf.length + " bytes long.");
}
// This could of course be optimized
int i;
for (i = 0; i < len; i++) {
int x = read();
if (x == -1 && i == 0) { // an immediate -1 returns -1
return -1;
}
else if (x == -1) { // a later -1 returns the chars read so far
break;
}
buf[off + i] = (byte) x;
}
return i;
}
/***
* Returns the decoded form of the given encoded string, as a String.
* Note that not all binary data can be represented as a String, so this
* method should only be used for encoded String data. Use decodeToBytes()
* otherwise.
*
* @param encoded the string to decode
* @return the decoded form of the encoded string
*/
public static String decode(String encoded) {
return new String(decodeToBytes(encoded));
}
/***
* Returns the decoded form of the given encoded string, as bytes.
*
* @param encoded the string to decode
* @return the decoded form of the encoded string
*/
public static byte[] decodeToBytes(String encoded) {
byte[] bytes = null;
try {
bytes = encoded.getBytes("UTF-8");
}
catch (UnsupportedEncodingException ignored) { }
Base64Decoder in = new Base64Decoder(
new ByteArrayInputStream(bytes));
ByteArrayOutputStream out =
new ByteArrayOutputStream((int) (bytes.length * 0.67));
try {
byte[] buf = new byte[4 * 1024]; // 4K buffer
int bytesRead;
while ((bytesRead = in.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
}
out.close();
return out.toByteArray();
}
catch (IOException ignored) { return null; }
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java Base64Decoder fileToDecode");
return;
}
Base64Decoder decoder = null;
try {
decoder = new Base64Decoder(
new BufferedInputStream(
new FileInputStream(args[0])));
byte[] buf = new byte[4 * 1024]; // 4K buffer
int bytesRead;
while ((bytesRead = decoder.read(buf)) != -1) {
System.out.write(buf, 0, bytesRead);
}
}
finally {
if (decoder != null) decoder.close();
}
}
}
package com.spacetech.common.utils;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class CDATAdapter extends XmlAdapter<String, String> {
@Override
public String unmarshal(String v) throws Exception {
return v;
}
@Override
public String marshal(String v) throws Exception {
return "<![CDATA[" + v + "]]>";
}
}
package com.spacetech.common.utils;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import com.spacetech.common.exception.ApiException;
public class CalcUtil {
private static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
private static final String CONDITION_UNION_TYPE_AND = "&&";
private static final String CONDITION_UNION_TYPE_OR = "||";
/**
* 判断条件是否满足
*
* @return
*/
public static boolean judgeAtomCondition(String atomCondition) {
// 肯定是数字型
if (atomCondition.indexOf(">=") > -1) {
String[] values = atomCondition.split(">=");
return judgeResult(values, ">=");
} else if (atomCondition.indexOf("<=") > -1) {
String[] values = atomCondition.split("<=");
return judgeResult(values, "<=");
} else if (atomCondition.indexOf(">") > -1) {
String[] values = atomCondition.split(">");
return judgeResult(values, ">");
} else if (atomCondition.indexOf("<") > -1) {
String[] values = atomCondition.split("<");
return judgeResult(values, "<");
} else if (atomCondition.indexOf("!=null") > -1) {
String[] values = atomCondition.split("!=");
// 不为空只有表单条件时候才有,如果表单数据为空,那么表达式不会被替换
if (values[0].equals("null") || values[0].indexOf("form#") > -1 || atomCondition.startsWith("!=")) {
return false;
}
return true;
} else if (atomCondition.indexOf("==") > -1) {
String[] values = atomCondition.split("==");
double value0 = jse(values[0]);
double value1 = jse(values[1]);
// ??? 除了 中文的 0=0无法比较,其他条件应该都可以比较
if (value0 > 0 && value0 == value1) {
return true;
} else {
return values[0].equals(values[1].trim());
}
} else if (atomCondition.indexOf("!=") > -1) {
String[] values = atomCondition.split("!=");
double value0 = jse(values[0]);
double value1 = jse(values[1]);
// ??? 除了 中文的 0=0无法比较,其他条件应该都可以比较
if (value0 > 0 && value0 == value1) {
return false;
} else {
return !values[0].equals(values[1].trim());
}
} else {
throw new RuntimeException("不正确的条件表达式" + atomCondition);
}
}
private static Double jse(String express) {
if (express != null && (express.indexOf("-") > 0 || express.indexOf("+") > 0 || express.indexOf("*") > 0
|| express.indexOf("/") > 0)) {
return eval(express);
} else {
return StringUtil.getDoubleOfObj(express);
}
}
private static boolean judgeResult(String[] values, String operator) {
for (Integer i = 1; i < values.length; i++) {
boolean result = false;
switch (operator) {
case "<=":
result = jse(values[i - 1]) <= jse(values[i]);
break;
case ">=":
result = jse(values[i - 1]) >= jse(values[i]);
break;
case ">":
result = jse(values[i - 1]) > jse(values[i]);
break;
case "<":
result = jse(values[i - 1]) < jse(values[i]);
break;
default:
result = false;
break;
}
if (!result) {
return false;
}
}
return true;
}
public static Double eval(String express) {
try {
return StringUtil.getDoubleOfObj(jse.eval(express));
} catch (ScriptException e) {
return 0d;
}
}
/**
* 表达式expression校验:checkNum<2;2<=checkNum<5;5<=checkNum
*
* @param checkNum
* @param expression
* @return
*/
public static Boolean checkExpression(Float checkNum, String expression) {
try {
if (expression.indexOf("<=") == -1) {
if (checkNum < StringUtil.getNullFloat(expression.split("<=")[2])) {
return true;
}
} else if (expression.split("<").length > 2) {
float min = StringUtil.getNullFloat(expression.split("<=")[0]);
float max = StringUtil.getNullFloat(expression.split("<")[2]);
if (min <= checkNum && checkNum < max) {
return true;
}
} else {
if (StringUtil.getNullFloat(expression.split("<=")[0]) <= checkNum) {
return true;
}
}
} catch (Exception e) {
throw new ApiException("表达式配置不正确");
}
return false;
}
/**
* B,KB,MB,GB 单位换算
*
*/
public static String fileSizeConver(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
}
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "MB";
} else if (fileS < 1099511627776L) {
fileSizeString = df.format((double) fileS / 1073741824) + "GB";
} else {
fileSizeString = df.format((double) fileS / 1099511627776L) + "TB";
}
return fileSizeString;
}
public static boolean isMatchRule(String expression) {
boolean result = false;
if (StringUtil.isNullOrEmpty(expression)) {
return result;
}
String unionType = CONDITION_UNION_TYPE_AND;
String splitValue = "";
if (expression.indexOf(CONDITION_UNION_TYPE_OR) > -1) {
unionType = CONDITION_UNION_TYPE_OR;
splitValue = "\\|\\|";
} else {
unionType = CONDITION_UNION_TYPE_AND;
splitValue = CONDITION_UNION_TYPE_AND;
}
expression = expression.replaceAll(" ", "");
String[] conditions = expression.split(splitValue);
for (String condition : conditions) {
// String replacedCondition = replaceFormExpressionWithValue(condition,
// dataList);
boolean conditionMeeted = judgeAtomCondition(condition);
if (unionType.equals(CONDITION_UNION_TYPE_AND)) {
if (!conditionMeeted) {
result = false;
break;
} else {
result = true;
}
}
if (unionType.equals(CONDITION_UNION_TYPE_OR) && conditionMeeted) {
result = true;
break;
}
}
return result;
}
/**
* 获取列表的中位数;
*
* @param numList
* @return
*/
public static Float getMedianNum(List<Float> numList){
if(numList.isEmpty()){
return 0.0f;
}
Collections.sort(numList);
int size = numList.size();
if (size % 2 == 1) { // size为奇数个
return numList.get((size - 1) / 2);
} else { //size 为偶数个
return (numList.get((size / 2 - 1)) + numList.get(size / 2)) / 2;
}
}
}
package com.spacetech.common.utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import com.spacetech.common.utils.FileUtil;
/**
* @author lc Date: 13-06-04
*/
public class ConfigUtil {
private static Properties props;
public static void loadProperties(String properties) {
props = new Properties();
try {
props.load(Thread.currentThread().getContextClassLoader()
.getResource(properties).openStream());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 得到key的值
*
* @param key
* 取得其值的键
* @return key的值
*/
public static String getValue(String key) {
if (props!=null && props.containsKey(key)) {
return props.getProperty(key);// 得到某一属性的值
} else {
return "";
}
}
/**
* 图片上传路径
*
* @param orgcde
* @return
*/
public static String getFileUploadPath() {
String fileUploadPath = ConfigUtil.getValue("share") + "/";
FileUtil.makeDir(fileUploadPath);
return fileUploadPath;
}
/**
* 改变或添加一个key的值,当key存在于properties文件中时该key的值被value所代替, 当key不存在时,该key的值是value
*
* @param key
* 要存入的键
* @param value
* 要存入的值
*/
public void setValue(String key, String value) {
props.setProperty(key, value);
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
package com.spacetech.common.utils;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExcelUtil {
private static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
public static Object getExcelValue(HSSFCell cell) {
if (cell == null) {
return null;
}
Object obj = null;
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
if (HSSFDateUtil.isCellDateFormatted(cell)) {
obj = cell.getDateCellValue();
try {
obj = DateUtil.dateToNormalString(cell.getDateCellValue());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} else {
obj = cell.getNumericCellValue();
obj = StringUtil.formartDecimal(obj);
}
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
obj = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
obj = cell.getBooleanCellValue();
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
obj = cell.getCellFormula();
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
break;
default:
obj = null;
break;
}
return obj;
}
/**
* 创建名称
*
* @param wb
* @param name
* @param expression
* @return
*/
public static HSSFName createName(HSSFWorkbook wb, String name,
String expression) {
HSSFName refer = wb.createName();
refer.setRefersToFormula(expression);
refer.setNameName(name);
return refer;
}
/**
* 设置数据有效性(通过名称管理器级联相关)
*
* @param name
* @param firstRow
* @param endRow
* @param firstCol
* @param endCol
* @return
*/
public static HSSFDataValidation setDataValidation(String name,
int firstRow, int endRow, int firstCol, int endCol) {
// 设置下拉列表的内容
logger.info("起始行:" + firstRow + "___起始列:" + firstCol + "___终止行:"
+ endRow + "___终止列:" + endCol);
// 加载下拉列表内容
DVConstraint constraint = DVConstraint
.createFormulaListConstraint(name);
// 设置数据有效性加载在哪个单元格上。
// 四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(
(short) firstRow, (short) endRow, (short) firstCol,
(short) endCol);
// 数据有效性对象
HSSFDataValidation data_validation = new HSSFDataValidation(regions,
constraint);
return data_validation;
}
/**
* 获取需要导入的字段,该字段设置在excel表格第二行
*
* @param row
* @return
*/
public static List<String> getRowCellColumnName(HSSFRow row) {
int lastCellNum = row.getLastCellNum();
List<String> columnNameList = new ArrayList<String>();
for (int i = 0; i <= lastCellNum; i++) {
if (row.getCell(i, HSSFRow.RETURN_BLANK_AS_NULL) == null) {
continue;
}
columnNameList.add(StringUtil.getNullStr(getExcelValue(row
.getCell(i))));
}
return columnNameList;
}
public static List<String> getRowTitle(HSSFRow row) {
int lastCellNum = row.getLastCellNum();
List<String> rowTitleList = new ArrayList<String>();
for (int i = 0; i <= lastCellNum; i++) {
if (row.getCell(i, HSSFRow.RETURN_BLANK_AS_NULL) == null) {
continue;
}
rowTitleList.add(StringUtil.getNullStr(getExcelValue(row
.getCell(i))));
}
return rowTitleList;
}
public static Object[] getRowData(HSSFRow row) {
int lastCellNum = row.getLastCellNum();
logger.info("getRowData lastCellNum="+lastCellNum);
Object[] rowData = new Object[lastCellNum];
for (int i = 0; i <= lastCellNum; i++) {
if (row.getCell(i, HSSFRow.RETURN_BLANK_AS_NULL) == null) {
continue;
}
rowData[i] = StringUtil.replaceBlank(StringUtil.getNullStr(getExcelValue(row.getCell(i))));
}
return rowData;
}
public static String getJsonSerialnumber(String serialnumber) {
StringBuilder columns = new StringBuilder();
columns.append("\"");
columns.append("serialnumber");
columns.append("\"");
columns.append(":");
columns.append("\"[");
columns.append(serialnumber);
columns.append("]\"");
return columns.toString();
}
public static String getJsonGriddata(String griddata) {
StringBuilder columns = new StringBuilder();
columns.append("\"");
columns.append("griddata");
columns.append("\"");
columns.append(":");
columns.append("\"[");
columns.append(griddata);
columns.append("]\"");
return columns.toString();
}
public static String getJsonErrorState(boolean errState) {
StringBuilder columns = new StringBuilder();
columns.append("\"");
columns.append("state");
columns.append("\"");
columns.append(":");
columns.append("\"[");
columns.append(errState);
columns.append("]\"");
return columns.toString();
}
public static String getImportRetunGrid(String jsonSerialnumber,
String JsonGriddata, String errstate) {
StringBuilder gridStr = new StringBuilder("{");
gridStr.append(jsonSerialnumber);
gridStr.append(",");
gridStr.append(JsonGriddata);
gridStr.append(",");
gridStr.append(errstate);
gridStr.append("}");
return gridStr.toString();
}
public static Object getExcelVaulue(HSSFCell cell) {
Object obj = null;
if (cell != null) {
switch (StringUtil.getIntOfObj(cell.getCellType())) {
case HSSFCell.CELL_TYPE_NUMERIC: // 数字
if (HSSFDateUtil.isCellDateFormatted(cell)) {
obj = cell.getDateCellValue();
try {
obj = DateUtil.dateToNormalString(cell
.getDateCellValue());
} catch (Exception e) {
logger.error(
" GET_EXCEL_VALUE ERROR , VALUE = "
+ cell.getDateCellValue(), e);
return null;
}
} else {
obj = cell.getNumericCellValue();
obj = StringUtil.formartDecimal(obj);
}
break;
case HSSFCell.CELL_TYPE_STRING: // 字符串
obj = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
obj = cell.getBooleanCellValue();
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
obj = cell.getCellFormula();
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
break;
default:
obj = null;
break;
}
}
return obj;
}
}
package com.spacetech.common.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FfmpegUtil {
private static final String FFMPEGPATH = "ffmpeg";
private static final String MP4 = ".mp4";
public static final String TEMPPATH = System.getProperties().getProperty("java.io.tmpdir")
+ System.getProperties().getProperty("file.separator");
private static Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);
private static final Integer HDAUDIOFREQ = 44100;
private static final Integer SDAUDIOFREQ = 22050;
private static final Integer HDAUDIOBIT = 128;
private static final Integer SDAUDIOBIT = 96;
private static final Integer HDVIDEOHEIGHT = 720;
private static final Integer SDVIDEOHEIGHT = 360;
private static final Integer HDVIDEOWIDTH = 1280;
private static final Integer SDVIDEOWIDTH = 640;
private static final Integer HDVIDEOBIT = 1000;
private static final Integer SDVIDEOBIT = 768;
/**
* 获取视频总时间
*
* @param viedo_path
* 视频路径
* @param ffmpeg_path
* ffmpeg路径
* @return
*/
public static Long getVideoTime(String videofilepath) {
logger.info(videofilepath + ":getTime");
List<String> commands = new java.util.ArrayList<String>();
commands.add(FFMPEGPATH);
commands.add("-i");
commands.add(videofilepath);
try {
ProcessBuilder builder = getProcessBuilder();
builder.command(commands);
final Process p = builder.start();
// 从输入流中读取视频信息
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
// 从视频信息中解析时长
String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
Pattern pattern = Pattern.compile(regexDuration);
Matcher m = pattern.matcher(sb.toString());
if (m.find()) {
Long time = getTimelen(m.group(1));
logger.error("getVideoTime return time " + time);
return time;
}
} catch (Exception e) {
logger.error("getVideoTime error", e);
}
logger.error("getVideoTime return 0");
return 0L;
}
// 格式:"00:00:10.68"
public static Long getTimelen(String timelen) {
Long min = 0L;
try{
if (StringUtil.isNullOrEmpty(timelen)) {
return min;
}
timelen = timelen.trim();
if (timelen.length() > 8) {
timelen = timelen.substring(0, 8);
}
String strs[] = timelen.split(":");
if (strs[0].compareTo("0") > 0) {
min += Integer.valueOf(strs[0]) * 60 * 60;// 秒
}
if (strs[1].compareTo("0") > 0) {
min += Integer.valueOf(strs[1]) * 60;
}
if (strs[2].compareTo("0") > 0) {
min += Float.valueOf(strs[2]).longValue();
}
}catch(Exception e){
logger.error("getvideo Duration error timelen"+timelen,e);
}
return min;
}
public static String makeImgbyvideo(String videofilepath, String imgfilepath, String widthAndHeigth,
Map<String, String> movieInfo) {
System.out.println(videofilepath + "->" + TEMPPATH + imgfilepath + ".bmp");
List<String> commend = new java.util.ArrayList<String>();
commend.add(FFMPEGPATH);
commend.add("-i");
commend.add(videofilepath);
commend.add("-y");
commend.add("-f");
commend.add("image2");
commend.add("-ss");
commend.add("00:00:01");
commend.add("-t");
commend.add("00:00:01");
commend.add("-s");
if (StringUtil.isNullOrEmpty(widthAndHeigth)) {
commend.add("320x200");
} else {
commend.add(widthAndHeigth);
}
commend.add(TEMPPATH + imgfilepath + ".jpg");
try {
ProcessBuilder builder = getProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
Process p = builder.start();
String line = null;
BufferedReader buf = null;
buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = buf.readLine()) != null) {
continue;
}
int ret = p.waitFor();
return TEMPPATH + imgfilepath + ".jpg";
} catch (Exception e) {
logger.error("makeImgbyvideo error", e);
return "";
}
}
public static String makeImgbyvideo(String videofilepath, String imgfilepath, String widthAndHeigth,
String startTime) {
List<String> commend = new java.util.ArrayList<String>();
commend.add(FFMPEGPATH);
commend.add("-i");
commend.add(videofilepath);
commend.add("-y");
commend.add("-f");
commend.add("image2");
commend.add("-ss");
commend.add(startTime);
commend.add("-t");
commend.add("00:00:01");
commend.add("-s");
if (StringUtil.isNullOrEmpty(widthAndHeigth)) {
commend.add("320x200");
} else {
commend.add(widthAndHeigth);
}
commend.add(TEMPPATH + imgfilepath + ".jpg");
try {
ProcessBuilder builder = getProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
Process p = builder.start();
String line = null;
BufferedReader buf = null;
buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = buf.readLine()) != null) {
continue;
}
int ret = p.waitFor();
return TEMPPATH + imgfilepath + ".jpg";
} catch (Exception e) {
logger.error("makeImgbyvideo18 error", e);
return "";
}
}
public static boolean encodeToFlvVideo(String videosrc, String videotar) {
System.out.println(videosrc + "->" + videotar);
try {
Map baseinfo = translateInfo(getMovieInfo(videosrc));
encode(getFlvInfoByBaseInfo(baseinfo), videotar);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static String encodeToMp4Video(String videosrc, String videotar) {
logger.info(videosrc + "->" + videotar);
try {
Map<String, String> baseinfo = FfmpegUtil.translateInfo(FfmpegUtil.getMovieInfo(videosrc));
if (baseinfo.get("videoEncode").contains("h264") && suffixIsMP4(videosrc)) {
return videosrc;
}
return encode(getMp4InfoByBaseInfo(baseinfo), videotar);
} catch (Exception e) {
logger.error("encodeToMp4Video videosrc=" + videosrc + " videotar=" + videotar, e);
return null;
}
}
private static boolean suffixIsMP4(String videosrc) {
int videoLength = videosrc.length();
return videoLength > 4 && videosrc.substring(videoLength - 4).equalsIgnoreCase(MP4);
}
public static String getVedioTime(String videosrc) {
return translateInfo(getMovieInfo(videosrc)).get("duration");
}
/**
* 通过ffmpeg获取影片的信息
*
* @param movieUrl
* <a href="http://my.oschina.net/u/556800" class="referer" target=
* "_blank">@return</a>
*/
public static Map<String, String> getMovieInfo(String movieFfmpegUrl) {
try {
List<String> command = new java.util.ArrayList<String>();
command.add(FFMPEGPATH);
command.add("-i");
command.add(movieFfmpegUrl);
ProcessBuilder builder = getProcessBuilder();
builder.command(command);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader buf = null;
String line = null;
buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
Map<String, String> info = new HashMap<String, String>();
info.put("filepath", movieFfmpegUrl);
while ((line = buf.readLine()) != null) {
// System.out.println(line);
if (line.contains("Duration:")) {
info.put("Duration", (line.substring(line.indexOf("Duration:") + 9)).trim());
} else if (line.contains("Video:")) {
info.put("Video", line.substring(line.indexOf("Video:") + 6));
} else if (line.contains("Audio:")) {
info.put("Audio", line.substring(line.indexOf("Audio:") + 6));
}
continue;
}
int ret = p.waitFor();
return info;
} catch (Exception e) {
logger.error("movieFfmpegUrl="+movieFfmpegUrl+" error"+e.getMessage(),e);
}
return null;
}
private static Map<String, String> translateInfo(Map<String, String> info) {
String duration = info.get("Duration").split(",")[0];
String audio = info.get("Audio");
String audiofreq = "";
String audiobit = "";
String video = info.get("Video");
String videobit = "";
String videoheight = "";
String videowidth = "";
String videoEncode = "";
String videotbn = null;
if (audio != null) {
for (String subinfo : audio.split(",")) {
if (subinfo.contains("Hz")) {
audiofreq = subinfo.substring(0, subinfo.indexOf("Hz")).trim();
} else if (subinfo.contains("kb/s")) {
audiobit = subinfo.substring(0, subinfo.indexOf("kb/s")).trim();
}
}
}
String[] videoInfos = video.split(",");
videoEncode = videoInfos[0];
for (int i = 1; i < videoInfos.length; i++) {
String subinfo = videoInfos[i];
if (subinfo.contains("x")) {
videowidth = subinfo.split("x")[0].trim();
videoheight = subinfo.split("x")[1].trim();
} else if (subinfo.contains("kb/s")) {
videobit = subinfo.substring(0, subinfo.indexOf("kb/s")).trim();
} else if (subinfo.contains("tbn")) {
videotbn = subinfo.substring(0, subinfo.indexOf("tbn")).trim();
}
}
Map<String, String> finalInfo = new HashMap<String, String>();
finalInfo.put("duration", duration);
finalInfo.put("videoEncode", videoEncode);
finalInfo.put("audiofreq", StringUtil.getQuantity(audiofreq));
finalInfo.put("audiobit", StringUtil.getQuantity(audiobit));
finalInfo.put("videobit", StringUtil.getQuantity(videobit));
finalInfo.put("videoheight", StringUtil.getQuantity(videoheight));
finalInfo.put("videowidth", StringUtil.getQuantity(videowidth));
finalInfo.put("filepath", info.get("filepath"));
return finalInfo;
}
private static Map<String, String> getFlvInfoByBaseInfo(Map<String, String> info) {
Map<String, String> HDInfo = new HashMap(info);
HDInfo.put("codec", "libx264");
HDInfo.put("quality", ".HD.flv");
if (StringUtil.isNullOrEmpty(info.get("audiofreq")) || Integer.parseInt(info.get("audiofreq")) > HDAUDIOFREQ) {
HDInfo.put("audiofreq", HDAUDIOFREQ.toString());
}
if (StringUtil.isNullOrEmpty(info.get("audiobit")) || Integer.parseInt(info.get("audiobit")) > HDAUDIOBIT) {
HDInfo.put("audiobit", HDAUDIOBIT.toString());
}
if (StringUtil.isNullOrEmpty(info.get("videobit")) || Integer.parseInt(info.get("videobit")) > HDVIDEOBIT) {
HDInfo.put("videobit", HDVIDEOBIT.toString());
}
if (StringUtil.isNotEmpty(info.get("videoheight"))) {
int height = Integer.parseInt(info.get("videoheight"));
int width = Integer.parseInt(info.get("videowidth"));
if (height > width) { // 竖屏
if (height > HDVIDEOWIDTH) {
HDInfo.put("videoheight", HDVIDEOWIDTH.toString());
}
if (width > HDVIDEOHEIGHT) {
HDInfo.put("videowidth", HDVIDEOHEIGHT.toString());
}
} else {
if (height > HDVIDEOHEIGHT) {
HDInfo.put("videoheight", HDVIDEOHEIGHT.toString());
}
if (width > HDVIDEOWIDTH) {
HDInfo.put("videowidth", HDVIDEOWIDTH.toString());
}
}
} else {
HDInfo.put("videoheight", HDVIDEOHEIGHT.toString());
HDInfo.put("videowidth", HDVIDEOWIDTH.toString());
}
return HDInfo;
}
private static Map<String, String> getMp4InfoByBaseInfo(Map<String, String> info) {
Map<String, String> HDInfo = new HashMap(info);
HDInfo.put("codec", "libx264");
HDInfo.put("quality", ".HD.mp4");
if (StringUtil.isNullOrEmpty(info.get("audiofreq")) || Integer.parseInt(info.get("audiofreq")) > HDAUDIOFREQ) {
HDInfo.put("audiofreq", HDAUDIOFREQ.toString());
}
if (StringUtil.isNullOrEmpty(info.get("audiobit")) || Integer.parseInt(info.get("audiobit")) > HDAUDIOBIT) {
HDInfo.put("audiobit", HDAUDIOBIT.toString());
}
if (StringUtil.isNullOrEmpty(info.get("videobit")) || Integer.parseInt(info.get("videobit")) > HDVIDEOBIT) {
HDInfo.put("videobit", HDVIDEOBIT.toString());
}
if (StringUtil.isNotEmpty(info.get("videoheight"))) {
int height = Integer.parseInt(info.get("videoheight"));
int width = Integer.parseInt(info.get("videowidth"));
if (height > width) { // 竖屏
if (height > HDVIDEOWIDTH) {
HDInfo.put("videoheight", HDVIDEOWIDTH.toString());
}
if (width > HDVIDEOHEIGHT) {
HDInfo.put("videowidth", HDVIDEOHEIGHT.toString());
}
} else {
if (height > HDVIDEOHEIGHT) {
HDInfo.put("videoheight", HDVIDEOHEIGHT.toString());
}
if (width > HDVIDEOWIDTH) {
HDInfo.put("videowidth", HDVIDEOWIDTH.toString());
}
}
} else {
HDInfo.put("videoheight", HDVIDEOHEIGHT.toString());
HDInfo.put("videowidth", HDVIDEOWIDTH.toString());
}
return HDInfo;
}
private static Map<String, String> getSDInfoByBaseInfo(Map<String, String> info) {
Map<String, String> SDInfo = new HashMap(info);
SDInfo.put("codec", "mpeg4");
SDInfo.put("quality", ".SD.mp4");
if (StringUtil.isNullOrEmpty(info.get("audiofreq")) || Integer.parseInt(info.get("audiofreq")) > SDAUDIOFREQ) {
SDInfo.put("audiofreq", SDAUDIOFREQ.toString());
}
if (StringUtil.isNullOrEmpty(info.get("audiobit")) || Integer.parseInt(info.get("audiobit")) > SDAUDIOBIT) {
SDInfo.put("audiobit", SDAUDIOBIT.toString());
}
if (StringUtil.isNullOrEmpty(info.get("videobit")) || Integer.parseInt(info.get("videobit")) > SDVIDEOBIT) {
SDInfo.put("videobit", SDVIDEOBIT.toString());
}
if (StringUtil.isNotEmpty(info.get("videoheight"))) {
int height = Integer.parseInt(info.get("videoheight"));
int width = Integer.parseInt(info.get("videowidth"));
if (height > width) { // 竖屏
if (height > SDVIDEOWIDTH) {
SDInfo.put("videoheight", SDVIDEOWIDTH.toString());
}
if (width > SDVIDEOHEIGHT) {
SDInfo.put("videowidth", SDVIDEOHEIGHT.toString());
}
} else {
if (height > SDVIDEOHEIGHT) {
SDInfo.put("videoheight", SDVIDEOHEIGHT.toString());
}
if (width > SDVIDEOWIDTH) {
SDInfo.put("videowidth", SDVIDEOWIDTH.toString());
}
}
} else {
SDInfo.put("videoheight", SDVIDEOHEIGHT.toString());
SDInfo.put("videowidth", SDVIDEOWIDTH.toString());
}
return SDInfo;
}
private static String encode(Map<String, String> setting, String filepath) {
String tarFilename = TEMPPATH + filepath + setting.get("quality");
List<String> commend = new java.util.ArrayList<String>();
commend.add(FFMPEGPATH);
commend.add("-y");
commend.add("-i");
commend.add(setting.get("filepath"));
if (!setting.get("quality").endsWith("flv")) {
commend.add("-vcodec");
commend.add(setting.get("codec"));
}
commend.add("-vb");
commend.add(setting.get("videobit") + "k");
commend.add("-s");
commend.add(setting.get("videowidth") + "x" + setting.get("videoheight"));
// commend.add("-acodec");
// commend.add("libfaac");
// commend.add("-ab");
// commend.add(setting.get("audiobit") + "k");
// commend.add("-ar");
// commend.add(setting.get("audiofreq"));
commend.add(tarFilename);
try {
ProcessBuilder builder = getProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
Process p = builder.start();
String line = null;
BufferedReader buf = null;
buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = buf.readLine()) != null) {
continue;
}
int ret = p.waitFor();
FfmpegUtil.translateInfo(FfmpegUtil.getMovieInfo(tarFilename));
return tarFilename;
} catch (Exception e) {
logger.error("视频转码错误"+filepath+ " 原因:"+e.getMessage(),e);
return null;
}
}
public static String encodeAmrToMp3(String source, String target) {
List<String> commend = new java.util.ArrayList<String>();
commend.add(FFMPEGPATH);
commend.add("-y");
commend.add("-i");
commend.add(source);
commend.add("-acodec");
commend.add("libmp3lame");
commend.add("-ab");
commend.add("128");
commend.add("-ar");
commend.add("44100");
commend.add("-ac");
commend.add("2");
commend.add(target);
try {
ProcessBuilder builder = getProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
Process p = builder.start();
String line = null;
BufferedReader buf = null;
buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = buf.readLine()) != null) {
continue;
}
int ret = p.waitFor();
return target;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static ProcessBuilder builder;
private static ProcessBuilder getProcessBuilder() {
if (builder == null) {
try {
builder = new ProcessBuilder();
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("执行脚本命令错误,错误原因:" + e.getMessage(), e);
}
}
return builder;
}
public static void main(String[] args) {
// String filename =
// "/media/kfq/C/Users/FeiQuan/Desktop/新建文件夹/prj3.mp4";
// Map baseinfo = FfmpegUtil.translateInfo(FfmpegUtil
// .getMovieInfo(filename));
// System.out.println(baseinfo);
// Map hdinfo = FfmpegUtil.getHDInfoByBaseInfo(baseinfo);
// Map sdinfo = FfmpegUtil.getSDInfoByBaseInfo(baseinfo);
// Date start = new Date();
// // FfmpegUtil.encode(sdinfo, filename);
// Date second = new Date();
// System.out.println(second.getTime() - start.getTime());
// FfmpegUtil.encode(hdinfo, filename);
// System.out.println(new Date().getTime() - second.getTime());
}
}
package com.spacetech.common.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
public class FileHashUtil {
public static byte[] createChecksum(String filename) throws Exception {
InputStream fis = getFilename(filename);
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("SHA1");
int numRead;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
return complete.digest();
}
public static InputStream getFilename(String filename)
throws MalformedURLException, IOException, FileNotFoundException {
InputStream fis;
if (filename.length() > 4 && filename.substring(0, 4).equals("http")) {
URL url = new URL(filename);
fis = url.openStream();
} else {
fis = new FileInputStream(filename);
}
return fis;
}
/**
* 从文件名读取文件,并获取SHA1值
*
* @param fis
* @return
* @throws Exception
*/
public static String getSHA1Checksum(String filename) throws Exception {
byte[] b = createChecksum(filename);
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
/**
* 从文件流获取SHA1值
*
* @param fis
* @return
* @throws Exception
*/
public static String getSHA1Checksum(InputStream fis) throws Exception {
byte[] b = createChecksum(fis);
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
public static byte[] createChecksum(InputStream fis) throws Exception {
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("SHA1");
int numRead;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
return complete.digest();
}
}
package com.spacetech.common.utils;
import com.spacetech.common.ConstantVar;
import com.spacetech.common.utils.QrUtil.QrUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FileUtil {
private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
private static final int BUFFER_SIZE = 2 * 1024;
/**
* 创建文件夹;
*
* @param sDir 需要创建的文件夹完整路径
* @return 成功创建||已经存在 true 创建失败 false
*/
public static boolean makeDir(String sDir) {
File file = new File(sDir);
return file.exists() ? true : file.mkdirs();
}
/**
* 获取文件类型 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
*
* @param fileName
* @return
*/
public static String getFileType(String fileName) {
// 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
/**
* 获取文件类型 获取上传的文件名,先得到/的位置,再截取从 /的下一个位置到文件的最后.的值,最后得到文件名
*
* @param fileName
* @return
*/
public static String getFileName(String fileName) {
// 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
return fileName.substring(fileName.lastIndexOf("/") + 1, fileName.lastIndexOf("."));
}
/**
* 获取文件名称+文件类型
*
* @param fileName
* @return
*/
public static String getFileNameAndType(String fileName) {
// 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
if (StringUtil.isNullOrEmpty(fileName)) {
return "";
}
return fileName.substring(fileName.lastIndexOf("/") + 1);
}
public static void main(String[] args) {
System.out
.println(getFileNameAndType("http://weixt-static.oss-cn-qingdao-internal.aliyuncs.com//a37b0ea8957fae252367b6b960aa57964fd1eda9.jpg"));
}
public static boolean delDiskFile(String filepath, String filename) {
File file = new File(filepath, filename);
if (file.exists()) {
file.delete(); // TODO:check and report success
}
return true;
}
public static String fileUploadNews(String imgStr, String fileUploadPath) throws IOException {
String filename = "";
String storeFilePath = "";
try {
// String fileType = "jpg";
String[] imageFile = imgStr.split("base64,");
String fileType = "";
if (imageFile[0].indexOf("audio") > -1) {
fileType = ConstantVar.RESOURCE_FORMAT_AUDIO;
} else {
fileType = imageFile[0].split(":")[1].split("/")[1].replace(";", "");
}
filename = StringUtil.getIdGenerator() + "." + fileType;
storeFilePath = fileUploadPath + filename;
GenerateImage(imageFile[1], storeFilePath);
} catch (Exception e) {
logger.error("广告推广-图片上传文件失败:" + e.getMessage());
}
return storeFilePath;
}
public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成jpeg图片
// imgFilePath =
// "/Users/hbz/work/share/10004/cytd/grittt1122123.jpg";// 新生成的图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
/**
* 图片转化成base64字符串
*
* @param filePath
* @return
*/
public static String getImageStr(String filePath, String storeFilePath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
String imgFile = "";
byte[] data = null;
try {
String fileType = "jpg";
String filename = StringUtil.getIdGenerator() + "." + fileType;
storeFilePath = storeFilePath + "/" + filename;
imgFile = FileUtil.download(filePath, storeFilePath);
// 待处理的图片
InputStream in = null;
// 读取图片字节数组
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}
/**
* 设定文件存储路径,存数据库 如 logo/log10001.jpg
*
* @param fileName
* @return
*/
public static String getStoreFilePath(String path, String folder) {
makeDir(path + "/" + folder);// 不存在创建
return path + folder;
}
public static String createFile(String sourcePath) {
File file = new File(sourcePath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return sourcePath;
}
/**
* 获取文件类型 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
*
* @param fileName
* @return
*/
public static String getOrignFileName(String fileName) {
// 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
return fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
}
public static String getFilePath(String fileName) {
// 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
return fileName.substring(0, fileName.lastIndexOf("/") + 1);
}
/**
* 文件重命名
*
* @param oldFilePath
* @param newFileName
* @return
*/
public static boolean renameFile(String oldFilePath, String newFileName) {
File file = new File(oldFilePath);
String path = FileUtil.getFilePath(oldFilePath) + newFileName;
boolean result = false;
File newFile = new File(path);
if (!newFile.exists()) {
result = file.renameTo(newFile);
}
return result;
}
/**
* 创建文件
*
* @param realPath 本地文件保存根路径
* @param exportFolder 文件夹
* @param fileNameStart 文件名
* @param fileType 文件扩展名
* @return
*/
public static String createFile(String realPath, String exportFolder, String fileNameStart, String fileType) {
String fileName = fileNameStart + StringUtil.getIdGenerator() + fileType;
makeDir(realPath + "/" + exportFolder);
return exportFolder + "/" + fileName;
}
/**
* 保存多服务器共享文件
*
* @param inputStream
* @param fileType
* @return
*/
public static String writeByteFileTmpForServers(InputStream inputStream, String fileType, String localfileDic) {
if (StringUtil.isNullOrEmpty(localfileDic)) {
localfileDic = UtilConstant.WEIKE_FILE;
}
return writeByteFileTmp(inputStream, fileType, localfileDic);
}
/**
* 保存文件
*
* @param inputStream
* @param fileType
* @return
*/
private static String writeByteFileTmp(InputStream inputStream, String fileType, String outPath) {
String fileName = StringUtil.getIdGenerator() + "." + fileType;
File dir = new File(outPath, fileName);// 上传后写入硬盘的文件
OutputStream outputStream = null;// 输出流写到硬盘
try {
outputStream = new FileOutputStream(dir);
} catch (FileNotFoundException ex) {
logger.error(ex.getMessage());
}
// 读取输入流,并由输出流写入硬盘
try {
byte[] b = new byte[1024];
int len;
while ((len = inputStream.read(b)) != -1) {
outputStream.write(b, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
logger.error(ex.getMessage());
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 检查是否写入成功,成功的话给予提示 , 后续应该进行重构,保存和更新分离出来。
return outPath + fileName;
}
/**
* 将存放在sourceFilePath目录下的源文件,打包成fileName名称的zip文件,并存放到zipFilePath路径下
*
* @param sourceFilePath :待压缩的文件路径
* @param zipFilePath :压缩后存放路径
* @param fileName :压缩后文件的名称
* @return
*/
public static boolean fileToZip(String sourceFilePath, String zipFilePath, String fileName) {
boolean flag = false;
File sourceFile = new File(sourceFilePath);
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
ZipOutputStream zos = null;
if (sourceFile.exists() == false) {
System.out.println("待压缩的文件目录:" + sourceFilePath + "不存在.");
} else {
try {
File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
if (zipFile.exists()) {
System.out.println(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");
} else {
File[] sourceFiles = sourceFile.listFiles();
if (null == sourceFiles || sourceFiles.length < 1) {
System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");
} else {
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bufs = new byte[1024 * 10];
for (int i = 0; i < sourceFiles.length; i++) {
// 创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
bis = new BufferedInputStream(fis, 1024 * 10);
int read = 0;
while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
zos.write(bufs, 0, read);
}
}
flag = true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
// 关闭流
try {
if (null != bis)
bis.close();
if (null != zos)
zos.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
return flag;
}
public static boolean exists(String filepath, String filename) {
File file = new File(filepath, filename);
return file.exists();
}
public static String download(String filePath, String loadPath) throws Exception {
// 构造URL
URL url = new URL(filePath);
// 打开URL连接
URLConnection con = url.openConnection();
// 得到URL的输入流
InputStream input = con.getInputStream();
// 设置数据缓冲
byte[] bs = new byte[1024 * 2];
// 读取到的数据长度
int len;
// 输出的文件流保存图片至本地
OutputStream os = new FileOutputStream(loadPath);
while ((len = input.read(bs)) != -1) {
os.write(bs, 0, len);
}
os.close();
input.close();
return loadPath;
}
public static String changeToMp3(String mp3Path, String sourcePath) {
String targetPath = mp3Path + "msg_audio_" + StringUtil.getIdGenerator() + ".mp3";
File source = new File(sourcePath);
File target = new File(targetPath);
if (!target.exists()) {
try {
target.createNewFile();
} catch (IOException e) {
logger.error("mp3转换发生错误1=" + e.getMessage() + " mp3Path=" + mp3Path + " sourcePath=" + sourcePath, e);
}
}
// AudioAttributes audio = new AudioAttributes();
// Encoder encoder = new Encoder();
//
// audio.setCodec("libmp3lame");
// audio.setBitRate(new Integer(128000));
// audio.setChannels(new Integer(2));
// audio.setSamplingRate(new Integer(44100));
// EncodingAttributes attrs = new EncodingAttributes();
// attrs.setFormat("mp3");
// attrs.setAudioAttributes(audio);
// ffmpeg -i test.wav -acodec libmp3lame -ab 128 -ar 44100 -ac 2
// wav2amr.amr
try {
FfmpegUtil.encodeAmrToMp3(sourcePath, targetPath);
} catch (Exception e) {
logger.error("mp3转换发生错误2=" + e.getMessage() + " mp3Path=" + targetPath + " sourcePath=" + sourcePath, e);
}
return targetPath;
}
public static InputStream getInputStream(String strUrl) {
int nStartPos = 0;
HttpURLConnection urlconnection = null;
URL url = null;
InputStream fis = null;
try {
url = new URL(strUrl);
urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setRequestProperty("User-Agent", "Internet Explorer");
String sProperty = "bytes=" + nStartPos + "-";
// 告诉服务器book.rar这个文件从nStartPos字节开始传
urlconnection.setRequestProperty("RANGE", sProperty);
urlconnection.connect();
fis = urlconnection.getInputStream();
return fis;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.getMessage());
return null;
}
}
/**
* 根据业务路径生成二维码
*
* @param url 业务路径
* @param path 容器路径地址
* @return
*/
public static String bulidTwoDimensionCode(String realpath, String url) {
String storeFileName = realpath + "/two_dimension_code_" + StringUtil.getIdGenerator() + ".jpg";
try {
return QrUtil.getQRcode(storeFileName, "", url, false, "");
} catch (Exception e) {
e.printStackTrace();
logger.error("生成二维码路径错误:" + e.getMessage(), e);
return "";
}
}
/**
* 压缩成ZIP 方法1
*
* @param srcDir 压缩文件夹路径
* @param out 压缩文件输出流
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(String srcDir, String zipFilePath, boolean KeepDirStructure) throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
FileOutputStream out = null;
try {
out = new FileOutputStream(new File(zipFilePath));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils", e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 递归压缩方法
*
* @param sourceFile 源文件
* @param zos zip输出流
* @param name 压缩后的名称
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure)
throws Exception {
byte[] buf = new byte[BUFFER_SIZE];
if (sourceFile.isFile()) {
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if (listFiles == null || listFiles.length == 0) {
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if (KeepDirStructure) {
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();
}
} else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
} else {
compress(file, zos, file.getName(), KeepDirStructure);
}
}
}
}
}
/**
* 删除单个文件
*
* @param fileName 要删除的文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
// 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
if (file.exists() && file.isFile()) {
if (file.delete()) {
System.out.println("删除单个文件" + fileName + "成功!");
return true;
} else {
System.out.println("删除单个文件" + fileName + "失败!");
return false;
}
} else {
System.out.println("删除单个文件失败:" + fileName + "不存在!");
return false;
}
}
/**
* 删除目录及目录下的文件
*
* @param dir 要删除的目录的文件路径
* @return 目录删除成功返回true,否则返回false
*/
public static boolean deleteDirectory(String dir) {
// 如果dir不以文件分隔符结尾,自动添加文件分隔符
if (!dir.endsWith(File.separator))
dir = dir + File.separator;
File dirFile = new File(dir);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
System.out.println("删除目录失败:" + dir + "不存在!");
return false;
}
boolean flag = true;
// 删除文件夹中的所有文件包括子目录
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = FileUtil.deleteFile(files[i].getAbsolutePath());
if (!flag)
break;
}
// 删除子目录
else if (files[i].isDirectory()) {
flag = FileUtil.deleteDirectory(files[i].getAbsolutePath());
if (!flag)
break;
}
}
if (!flag) {
System.out.println("删除目录失败!");
return false;
}
// 删除当前目录
if (dirFile.delete()) {
System.out.println("删除目录" + dir + "成功!");
return true;
} else {
return false;
}
}
/**
* 根据业务路径批量下载图片到本地
*
* @param loadPath 本地容器路径地址
* @param photoList 业务内容
* @return
*/
public static void batchDownload(String loadPath, List<String> photoList) {
FileUtil.deleteDirectory(loadPath);
FileUtil.makeDir(loadPath);
int index = 0;
for (String photo : photoList) {
try {
logger.info("开始图片生成操作-" + index);
FileUtil.download(photo, loadPath + "/" + getFileNameAndType(photo));
index++;
logger.info("完成图片生成操作-" + index + " 图片地址:" + StringUtil.getNullStr(photo));
} catch (Exception e) {
logger.error("图片生成出错" + index + " 图片地址:" + StringUtil.getNullStr(photo) + " 错误原因:" + e.getMessage(), e);
}
}
}
/**
* 根据业务路径上传.zip文件至阿里云,然后删除本地临时文件夹
*
* @param loadPath 本地容器路径地址
* @return url 阿里云地址
*/
public static String zipFileToOSS(String loadPath, String zipFilePath, Boolean internal) {
String url = "";
try {
url = OSSClientUtil.putExportFileWithOrignName(zipFilePath, internal);
logger.info("完成图片生成后-打包完成-上传阿里云完成 : " + url);
} catch (Exception e) {
logger.info("上传阿里云出错");
}
FileUtil.deleteDirectory(loadPath);
return url;
}
public static String processBase64Img(String imgStr, Boolean internal, Boolean saveLocalfile,
String localfileInternet) {
if (StringUtil.isNullOrEmpty(imgStr)) {
return "";
}
if (imgStr.indexOf("base64,") > -1) {
return fileUploadNews(imgStr, "/tmp/", internal, saveLocalfile, localfileInternet);
} else {
return generateImage(imgStr, "/tmp/", internal, saveLocalfile, localfileInternet);
}
}
// base64字符串转化成图片
public static String generateImage(String imgStr, String filePath, Boolean internal, Boolean saveLocalfile,
String localfileInternet) { // 对字节数组字符串进行Base64解码并生成图片
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成jpeg图片
String imgFilePath = filePath + StringUtil.randomstr() + ".jpg"; // 文件的全路径,绝对路径名加文件名
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
String ossFileName = OSSClientUtil.putFile(imgFilePath, false, internal, saveLocalfile, localfileInternet);
return ossFileName;
} catch (Exception e) {
logger.error("电子班牌-图片上传文件失败1:" + e.getMessage(), e);
return "";
}
}
public static String fileUploadNews(String imgStr, String fileUploadPath, Boolean internal, Boolean saveLocalfile,
String localfileInternet) {
String filename = "";
String storeFilePath = "";
try {
// String fileType = "jpg";
String[] imageFile = imgStr.split("base64,");
// String fileType = imageFile[0].split(":")[1].split("/")[1].replace(";", "");
// filename = StringUtil.getIdGenerator() + "." + fileType;
// storeFilePath = fileUploadPath + filename;
return generateImage(imageFile[1], fileUploadPath, internal, saveLocalfile, localfileInternet);
} catch (Exception e) {
logger.error("电子班牌-图片上传文件失败2:" + e.getMessage(), e);
}
return storeFilePath;
}
/**
* @return java.lang.String
* @Author lz
* @Description 压缩图片 若图片大小小于500KB,则不压缩
* @Date 5:45 下午 2020/8/20
* @Param [picSrc]
**/
public static String compressPic(String picSrc) {
try {
File file = new File(picSrc);
if (!file.exists()) {
return null;
}
if (file.length() <= 500 * 1024) {
return picSrc;
}
String[] picNames = picSrc.split("\\.");
String minPicSrc = picNames[0] + "_mini." + picNames[1];
BufferedImage originalImage = null;
originalImage = ImageIO.read(new File(picSrc));
Thumbnails.of(originalImage).scale(0.25).toFile(minPicSrc);
logger.info("FileUtil_compressPic,图片压缩成功:filePath:" + minPicSrc);
return minPicSrc;
} catch (IOException e) {
logger.warn("FileUtil_compressPic 图片压缩失败 picSrc=" + picSrc, e);
return picSrc;
} catch (Exception e) {
logger.warn("FileUtil_compressPic 图片文件错误或后缀错误 picSrc=" + picSrc, e);
return picSrc;
}
}
}
package com.spacetech.common.utils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.methods.HttpPut;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class HttpClientUtil {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
public static UrlEncodedFormEntity getPostParam(Map<String, String> param) throws UnsupportedEncodingException {
List<NameValuePair> params = getReqParamNVP(param);
// 编码格式转换
return new UrlEncodedFormEntity(params, "utf-8");
}
public static List<NameValuePair> getReqParamNVP(Map<String, String> param) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
java.util.Iterator it = param.entrySet().iterator();
while (it.hasNext()) {
java.util.Map.Entry<String, String> entry = (java.util.Map.Entry<String, String>) it.next();
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));// entry.getKey()
// 返回与此项对应的键,entry.getValue(),返回与此项对应的值,logger.info(entry.getValue());
}
return params;
}
public static void main2(String[] args) {
String url = "http://localhost:8080/integtest/login";
Map<String, String> params = new HashMap<String, String>();
params.put("username", "admin");
params.put("password", "zaq1234");
try {
Map<String, String> sessoinMap = submitPostRequest(url, params, null);
String session = sessoinMap.get("Cookie");
if (session != null && !session.equals("")) {
Map<String, String> cookieMap = new HashMap<String, String>();
cookieMap.put("Cookie", session);
HashMap<String, String> paramsw = new HashMap<String, String>();
paramsw.put("params", "{}");
Map<String, String> resultMap = submitPostRequest("http://localhost:8080/integtest/api/user_list",
paramsw, cookieMap);
System.out.println(resultMap.get("responseMessage"));
// {"apiState":"ALL","apiStr":"","developer":"","pageInx":1,"pageSize":5,"pageTotal":0}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String execCmd(String cmd) {
StringBuffer result = new StringBuffer();
BufferedReader br = null;
InputStream os = null;
try {
Process proc = Runtime.getRuntime().exec(cmd);
os = proc.getInputStream();
br = new BufferedReader(new InputStreamReader(os));
String line;
while ((line = br.readLine()) != null) {
result.append(line).append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
closeIOConnection(os, null, br);
} catch (IOException e) {
logger.error("关闭IO异常" + e.getMessage());
}
}
return result.toString();
}
public final static String E_NETWORK_URL = "http://122.225.101.119:8085";
public static void main(String[] args) {
String synchronizeVideo = E_NETWORK_URL + "/eAPI/GetCourseByTime.ashx";
// {"etime":"2017-01-19","stime":"2017-01-18","token":"0d78fb004b7520b53c7bdc4c8ed957d1"}
System.out.println(execCmd("telnet localhost 8083"));
;
String url = "http://localhost:8080/integtest/login";
Map<String, String> params = new HashMap<String, String>();
params.put("username", "admin");
params.put("password", "zaq1234");
try {
JSONObject jsonParam = new JSONObject();
jsonParam.put("stime", "2016-01-18");
jsonParam.put("etime", "2017-01-19");
jsonParam.put("token", "0d78fb004b7520b53c7bdc4c8ed957d1");
JSONObject sessoinMap = httpPost(synchronizeVideo, jsonParam);
System.out.println(JSON.toJSONString(sessoinMap));
// String session = sessoinMap.get("Cookie");
// if (session != null && !session.equals("")) {
// Map<String, String> cookieMap = new HashMap<String, String>();
// cookieMap.put("Cookie", session);
// String gitparams = "{\"object_attributes\": {\"id\":
// 1516,\"target_branch\": \"master\",\"source_branch\":
// \"master_zh_0401_01\",\"source_project_id\": 49,\"author_id\":
// 7,\"assignee_id\": 12,\"title\":
// \"修改测试用例findbyid接口返回格式\",\"created_at\": \"2016-04-01 00:53:24
// UTC\",\"updated_at\": \"2016-04-01 00:57:17 UTC\",\"state\":
// \"merged\",\"merge_status\":
// \"can_be_merged\",\"target_project_id\": 49,\"iid\":
// 31,\"description\": \"\",\"position\": 0,\"source\":
// {\"name\":\"integratetest\",\"ssh_url\":
// \"git@10.10.10.191:yjf/integratetest.git\",\"http_url\":
// \"http://10.10.10.191/yjf/integratetest.git\",\"namespace\":
// \"yjf\",\"visibility_level\": 20},\"target\": {\"name\":
// \"integratetest\",\"ssh_url\":
// \"git@10.10.10.191:yjf/integratetest.git\",\"http_url\":
// \"http://10.10.10.191/yjf/integratetest.git\",\"namespace\":
// \"yjf\",\"visibility_level\": 20},\"last_commit\": {\"id\":
// \"d0a9de52100105b741b024cc32a7459f01af081e\",\"message\":
// \"[deployapi:api_list]修改测试用例findbyid接口返回格式\n\",\"timestamp\":
// \"2016-04-01T10:09:50+08:00\",\"url\":
// \"http://10.10.10.191/yjf/integratetest/commit/d0a9de52100105b741b024cc32a7459f01af081e\",\"author\":
// {\"name\": \"zhanghao\",\"email\":
// \"zhanghao@spacetech.com.cn\"}},\"url\":
// \"http://10.10.10.191/yjf/integratetest/merge_requests/31\",\"action\":
// \"open\"},\"object_kind\": \"merge_request\",\"user\": {\"name\":
// \"刘晓滨\",\"username\": \"lxb\",\"avatar_url\":
// \"http://gravatar.duoshuo.com/avatar/32624fabb0025c62aa65c72deed10ed8?s=40&d=identicon\"}}";
// HashMap<String, String> paramsw = new HashMap<String, String>();
// paramsw.put("params", gitparams);
// Map<String, String> resultMap = submitPostRequest(
// "http://localhost:8080/integtest/githook/mock",
// paramsw, cookieMap);
// System.out.println(resultMap.get("responseMessage"));
// //
// {"apiState":"ALL","apiStr":"","developer":"","pageInx":1,"pageSize":5,"pageTotal":0}
// }
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Map<String, String> submitPostRequest(String url, Map<String, String> postParamMap,
Map<String, String> requestHeaderMap) throws UnsupportedEncodingException {
return submitPostRequest(url, getPostParam(postParamMap), requestHeaderMap);
}
/**
* http post请求
*
* @param url
* @param param
* @return
* @throws ClientProtocolException
* @throws IOException
*/
public static JSONObject authPostRequest(String url, JSONObject param) {
JSONObject result = new JSONObject();
String responseStr = null;
try {
responseStr = httpPostWithJSON(url, JSON.toJSONString(param));
if (StringUtil.isNotEmpty(responseStr)) {
result = JSON.parseObject(StringUtil.unicodeToString(responseStr));
}
} catch (Exception e) {
e.printStackTrace();
logger.error("authPostRequest请求错误" + e.getMessage() + "入参url=" + url + " param=" + param + " responseStr="
+ responseStr);
}
return result;
}
/**
* 提交 POST 请求到腾讯服务器-官方接口调用
*
* @param url
* 携带access_token
* @param param
* @return
* @throws IOException
* @throws ClientProtocolException
*/
public static Map<String, String> authSubmitPostRequest(String url, String param, String hashkey)
throws ClientProtocolException, IOException {
HashMap<String, String> resultMap = new HashMap<String, String>();
resultMap.put("responseMessage", postRequest(url, param));
return resultMap;
}
public static String postRequest(String url, String param) throws ClientProtocolException, IOException {
long size = 0;
size += url.length();
long s0 = System.currentTimeMillis();
long s2 = 0;
InputStream is = null;
HttpClient client = getHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = null;
String result = "";
try {
if (param != null) {
StringEntity entity = new StringEntity(param, "utf-8");
entity.setContentType("text/json");
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(entity);
}
long s1 = System.currentTimeMillis();
response = client.execute(post);
HttpEntity entity = response.getEntity();
s2 = System.currentTimeMillis();
if (entity != null) {
// start 读取整个页面内容
is = entity.getContent();
// end 读取整个页面内容
result = readResponseInStream(is);
}
} finally {
try {
closeHttpConnection((CloseableHttpResponse) response, (DefaultHttpClient) client, null, post, null);
closeIOConnection(is,null,null);
} catch (Exception e) {
// //e.printStackTrace();
logger.error("提交微信HTTP请求出错:" + e.getMessage());
}
}
long s3 = System.currentTimeMillis();
return result;
}
// public static CloseableHttpClient getHttpClient() {
//
// PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
// cm.setMaxTotal(200);// 连接池最大并发连接数
// cm.setDefaultMaxPerRoute(50);// 单路由最大并发数
//
// HttpClient httpClient = HttpClients.custom()
// .setConnectionManager(cm).build();
//
// return httpClient;
// }
/**
* 提交GET 请求到服务器
*
* @param url
* @return
*/
public static Map<String, String> authSubmitGetRequest(String url) {
return authSubmitGetRequest(url, new HashMap<String, String>());
}
/**
* 提交GET 请求到服务器
*
* @param url
* @return
*/
public static Map<String, String> authSubmitGetRequest(String url, Map<String, String> header) {
long s0 = System.currentTimeMillis();
long s2 = 0;
InputStream is = null;
HttpClient client = getHttpClient();
HttpGet httpGet = new HttpGet(url);
for (Map.Entry<String, String> entry : header.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
HashMap<String, String> resultMap = new HashMap<String, String>();
HttpResponse response = null;
try {
long s1 = System.currentTimeMillis();
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
is = entity.getContent();// start 读取整个页面内容
resultMap.put("responseMessage", readResponseInStream(is)); // end
// 读取整个页面内容
}
logger.info("end authSubmitGetRequest ,response=" + resultMap.get("responseMessage"));
s2 = System.currentTimeMillis();
}
catch (java.net.ConnectException e) {
logger.error("网络异常:url=" + url + " 错误消息:" + e.getMessage());
// e.printStackTrace();
} catch (Exception e) {
logger.error(e.getMessage() + " URL=" + url);
// e.printStackTrace();
} finally {
try {
closeIOConnection(is, null ,null);
closeHttpConnection((CloseableHttpResponse) response, (DefaultHttpClient) client, httpGet, null, null);
} catch (Exception e) {
logger.error("关闭请求资源异常" + e);
}
}
return resultMap;
}
private static String parseJesssionId(HttpResponse response) {
String result = "";
if (response.getHeaders("Set-Cookie") != null && response.getHeaders("Set-Cookie").length > 0) {
String cookieSession = response.getHeaders("Set-Cookie")[0].toString();
String[] cookies = cookieSession.split(";");
for (String cookie : cookies) {
int jsessionIndex = cookie.indexOf("JSESSIONID");
if (jsessionIndex > 0) {
return cookie.substring(jsessionIndex, cookie.length());
}
}
}
return result;
}
/**
* 提交 POST 请求到服务器
*
* @param requestType
* 请求业务类型
* @param url
* 要POST的url,如果参数不多的话可以将参数直接设置到url中
* @param cookie
* @param referer
* @param param
* 要post到服务器的参数
* @return POST后的 response和cookie
*/
public static Map<String, String> submitPostRequest(String url, UrlEncodedFormEntity param,
Map<String, String> requestHeaderMap) {
// logger.info("begin submitPostRequest url=" + url);
HttpPost post = new HttpPost(url);
HttpResponse response = null;
InputStream is = null;
DefaultHttpClient client = getHttpClient();
HashMap<String, String> resultMap = new HashMap<String, String>();
try {
setRequestHeader(requestHeaderMap, post);
if (param != null) {
post.setEntity(param);
}
response = client.execute(post);
String jsessoiId = parseJesssionId(response);
resultMap.put("Cookie", jsessoiId);
resultMap.put("status", response.getStatusLine().getStatusCode() + "");
HttpEntity entity = response.getEntity();
if (entity != null) {
is = entity.getContent();// start 读取整个页面内容
resultMap.put("responseMessage", readResponseInStream(is)); // end
// 读取整个页面内容
}
} catch (java.net.ConnectException e) {
logger.error("网络异常:url=" + url + " 错误消息:" + e.getMessage());
// e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage() + " URL=" + url);
// e.printStackTrace();
} finally {
try {
closeIOConnection(is,null,null);
closeHttpConnection((CloseableHttpResponse) response, client, null, post, null);
} catch (Exception e) {
// e.printStackTrace();
logger.error("关闭请求资源异常" + e);
}
}
return resultMap;
}
private static String readResponseInStream(InputStream is) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
closeIOConnection(null, null, in);
return buffer.toString();
}
private static void setRequestHeader(Map<String, String> requestHeaderMap, HttpPost post) {
if (requestHeaderMap != null) {
Iterator iter = requestHeaderMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
if (entry.getValue() != null) {
post.setHeader(entry.getKey(), entry.getValue());
}
}
}
}
/**
* 模拟登录服务器,调用API,并返回结果
*
* @param baseUrl
* @param api
* @param params
* @param loginName
* @param password
* @return
*/
public static String callApi(String baseUrl, String api, String params, String loginName, String password) {
JSONObject result = new JSONObject();
String loginUrl = baseUrl + "/login";
Map<String, String> loginParams = new HashMap<String, String>();
loginParams.put("username", "admin");
loginParams.put("password", "zaq1234");
try {
Map<String, String> sessoinMap = submitPostRequest(loginUrl, loginParams, null);
String session = sessoinMap.get("Cookie");
if (session != null && !session.equals("")) {
Map<String, String> cookieMap = new HashMap<String, String>();
cookieMap.put("Cookie", session);
HashMap<String, String> paramsw = new HashMap<String, String>();
paramsw.put("params", params);
Map<String, String> resultMap = submitPostRequest(baseUrl + "/api/" + api, paramsw, cookieMap);
return resultMap.get("responseMessage");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
* 提交GET 请求到服务器
*
* @param requestType
* 请求业务类别
* @param url
* 请求url
* @param cookie
* @param referer
* @return 请求的response和cookie
*/
public static Map<String, String> submitGetRequest(String url, Map<String, String> requestHeaderMap) {
HttpGet post = new HttpGet(url);
HashMap<String, String> resultMap = new HashMap<String, String>();
HttpResponse response = null;
DefaultHttpClient client = null;
try {
if (requestHeaderMap != null) {
Iterator iter = requestHeaderMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
if (entry.getValue() != null) {
post.setHeader(entry.getKey(), entry.getValue());
}
}
}
client = getHttpClient();
response = client.execute(post);
StringBuffer cookies = new StringBuffer();
Header[] hs = response.getAllHeaders();
for (Header h : hs) {
if ("Set-Cookie".equals(h.getName())) {
cookies.append(h.getValue()).append(";");
}
}
resultMap.put("status", response.getStatusLine().getStatusCode() + "");
resultMap.put("cookieVal", StringUtil.getNullStr(cookies).replace(" Path=/; Secure; HttpOnly;", ""));
resultMap.put("responseMessage", EntityUtils.toString(response.getEntity()));
}
catch (java.net.ConnectException e) {
logger.error("网络异常:" + e.getMessage());
// e.printStackTrace();
} catch (Exception e) {
logger.error(e.getMessage());
// e.printStackTrace();
} finally {
try {
closeHttpConnection((CloseableHttpResponse) response, client, post, null, null);
// response.close();
} catch (Exception e) {
logger.error("关闭请求资源异常" + e);
}
}
return resultMap;
}
/**
* 获取文件类型 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
*
* @param fileName
* @return
*/
private static String getFileType(String fileName) {
// 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
private final static String CRLF = "\r\n";
private final static String twoHyphens = "--";
private final static String BOUNDARY = "----WebKitFormBoundary3mCxd7ijjdKKBtAZ";
public static Map<String, String> postFileUploadRequest(String post_url, Map<String, String> requestHeaderMap,
String filename, String filepath) {
java.net.URLConnection connection = getPostConn(post_url, requestHeaderMap);
StringBuffer responseMessage = new StringBuffer();
InputStream in = null;
BufferedReader br = null;
OutputStream output = null;
InputStream fis = null;
HttpResponse response = null;
HttpClient client = new DefaultHttpClient();
logger.info("in postFileUploadRequest filepath=" + filepath);
HttpGet httpGet = new HttpGet(filepath);
Map<String, String> map = new HashMap<String, String>();
StringBuffer resSB = new StringBuffer();
StringBuffer resSB2 = new StringBuffer();
try {
// 从七牛下载文件,并上传到微信
response = client.execute(httpGet);
fis = response.getEntity().getContent();
/**
* 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。
* 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做:
*/
BufferedInputStream bis = new BufferedInputStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int ch;
while ((ch = bis.read()) != -1)
baos.write(ch);
byte[] fileData = baos.toByteArray();
String filetype = getFileType(filename);
// logger.info("fileData1=" + fileData);
// logger.info("fileData length=" + fileData.length);
// 设置request payload参数
resSB.append("--" + BOUNDARY);
resSB.append(CRLF);
resSB.append("Content-Disposition: form-data; name=\"");
resSB.append("uploadfile");
resSB.append("\"; filename=\"").append(filename).append("\"");
resSB.append(CRLF);
resSB.append("Content-Type: ").append("image/" + filetype);
resSB.append(CRLF);
resSB.append(CRLF);
resSB2.append(CRLF);
resSB2.append(twoHyphens + BOUNDARY);
resSB2.append(CRLF);
resSB2.append("Content-Disposition: form-data; name=\"");
resSB2.append("formId").append("\"");
resSB2.append(CRLF);
resSB2.append(CRLF);
resSB2.append(twoHyphens + BOUNDARY + twoHyphens);
resSB2.append(CRLF);
logger.info("resSB=\r\n" + resSB.toString());
// 设置HTTP头:
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
connection.setRequestProperty("Content-Length", String.valueOf(
resSB.toString().getBytes().length + fileData.length + resSB2.toString().getBytes().length));
output = connection.getOutputStream();
// 设置参数
output.write(resSB.toString().getBytes());
// 传输文件
output.write(fileData);
// 设置参数
output.write(resSB2.toString().getBytes());
output.flush();
int charCount = -1;
in = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
while ((charCount = br.read()) != -1) {
responseMessage.append((char) charCount);
}
closeIOConnection(bis, baos, null);
map.put("responseMessage", responseMessage.toString());
} catch (Exception ex) {
logger.error("resSB=\r\n" + resSB.toString());
logger.error("resSB=\r\n" + resSB2.toString());
ex.printStackTrace();
} finally {
try {
closeIOConnection(fis, output, br);
closeIOConnection(in, null, null);
closeHttpConnection((CloseableHttpResponse) response, (DefaultHttpClient) client, httpGet, null, null);
closeURLConnection((HttpURLConnection) connection);
} catch (Exception e) {
logger.error("关闭请求资源异常" + e);
// e.printStackTrace();
}
}
return map;
}
private static URLConnection getPostConn(String post_url, Map<String, String> requestHeaderMap) {
java.net.URLConnection connection;
try {
connection = new java.net.URL(post_url).openConnection();
connection.setDoOutput(true);
/**
* 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。
* 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做:
*/
// 发送cookie信息上去,以表明自己的身份,否则会被认为没有权限
Iterator iter = requestHeaderMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
if (entry.getValue() != null) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
return connection;
} catch (Exception e) {
// e.printStackTrace();
return null;
}
}
//
// /**
// * java.net实现 HTTP POST方法提交
// *
// * @param url
// * @param paramContent
// * @return
// */
public static JSONObject submitPost(String url, String paramContent) {
logger.error("submitPost ERROR , url = " + url + " ,param = " + paramContent);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
Map<String, String> resultMap = new HashMap<String, String>();
String responseString = "";
HttpResponse response = null;
try {
if (paramContent != null) {
post.setEntity(new StringEntity(paramContent, "utf-8"));
}
response = client.execute(post);
responseString = EntityUtils.toString(response.getEntity(), "utf-8");
return JSON.parseObject(StringUtil.unicodeToString(responseString));
} catch (Exception e) {
logger.error("submitPost ERROR , url = " + url + " ,param = " + paramContent + ",responseString="
+ responseString, e);
return null;
} finally {
try {
closeHttpConnection((CloseableHttpResponse) response, (DefaultHttpClient) client, null, post, null);
} catch (Exception e) {
logger.error("关闭请求资源异常" + e);
}
}
}
/**
* httpPost
*
* @param url
* 路径
* @param jsonParam
* 参数
* @return
*/
public static JSONObject httpPost(String url, JSONObject jsonParam) {
return httpPost(url, jsonParam, false);
}
/**
* post请求
*
* @param url
* url地址
* @param jsonParam
* 参数
* @param noNeedResponse
* 不需要返回结果
* @return
*/
public static JSONObject httpPost(String url, JSONObject jsonParam, boolean noNeedResponse) {
JSONObject jsonResult = null;
DefaultHttpClient httpClient = null;
HttpPost method = null;
HttpResponse result = null;
try {
// post请求返回结果
httpClient = new DefaultHttpClient();
method = new HttpPost(url);
method.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
if (null != jsonParam) {
// 解决中文乱码问题
StringEntity entity = new StringEntity(jsonParam.toString(), HTTP.UTF_8);
// entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
method.setEntity(entity);
}
result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/** 请求发送成功,并得到响应 **/
int statusCode = result.getStatusLine().getStatusCode();
if (statusCode == 200) {
String str = "";
try {
/** 读取服务器返回过来的json字符串数据 **/
str = EntityUtils.toString(result.getEntity());
if (noNeedResponse) {
return null;
}
/** 把json字符串转换成json对象 **/
jsonResult = JSON.parseObject(str);
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}
}
} catch (Exception e) {
logger.error("post请求提交失败:" + url, e);
}finally {
try {
closeHttpConnection((CloseableHttpResponse) result, httpClient, null, method, null);
}catch (Exception e) {
logger.error("关闭请求资源异常" + e);
}
}
return jsonResult;
}
/**
* 适合多线程的HttpClient,用httpClient4.2.1实现
*
* @return DefaultHttpClient
*/
public static DefaultHttpClient getHttpClient() {
// 设置组件参数, HTTP协议的版本,1.1/1.0/0.9
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
// 设置连接超时时间
int REQUEST_TIMEOUT = 10 * 1000; // 设置请求超时10秒钟
int SO_TIMEOUT = 10 * 1000; // 设置等待数据超时时间10秒钟
// HttpConnectionParams.setConnectionTimeout(params, REQUEST_TIMEOUT);
// HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT);
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, REQUEST_TIMEOUT);
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
// 设置访问协议
SchemeRegistry schreg = new SchemeRegistry();
schreg.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
schreg.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
// 多连接的线程安全的管理器
PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(schreg);
pccm.setDefaultMaxPerRoute(20); // 每个主机的最大并行链接数
pccm.setMaxTotal(100); // 客户端总并行链接最大数
DefaultHttpClient httpClient = new DefaultHttpClient(pccm, params);
return httpClient;
}
public static void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
// 防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
// 得到输入流
InputStream inputStream = conn.getInputStream();
// 获取自己数组
byte[] getData = readInputStream(inputStream);
// 文件保存位置
File saveDir = new File(savePath);
if (!saveDir.exists()) {
saveDir.mkdir();
}
File file = new File(saveDir + File.separator + fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
try {
closeURLConnection(conn);
closeIOConnection(inputStream, fos, null);
} catch (IOException e) {
logger.error("关闭请求资源异常" + e);
}
System.out.println("info:" + url + " download success");
}
/**
* 从输入流中获取字节数组
*
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
closeIOConnection(null, bos, null);
return bos.toByteArray();
}
public static JSONObject submitPostJSON(String url, JSONObject params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
Map<String, String> resultMap = new HashMap<String, String>();
HttpResponse response = null;
String responseString = "";
try {
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
// 构建请求参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
list.add(new BasicNameValuePair(StringUtil.getNullStr(entry.getKey()),
StringUtil.getNullStr(entry.getValue())));
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
post.setEntity(entity);
}
response = client.execute(post);
responseString = EntityUtils.toString(response.getEntity(), "utf-8");
return JSON.parseObject(StringUtil.unicodeToString(responseString));
} catch (Exception e) {
logger.error("submitPost ERROR , url = " + url + " ,param = " + JSON.toJSONString(params)
+ ",responseString=" + responseString, e);
return null;
} finally {
try {
closeHttpConnection((CloseableHttpResponse) response, (DefaultHttpClient) client, null, post, null);
} catch (Exception e) {
logger.error("关闭请求资源异常" + e);
}
}
}
private static final String APPLICATION_JSON = "application/json";
private static final String CONTENT_TYPE_TEXT_JSON = "text/json";
public static String httpPostWithJSON(String url, String param) throws Exception {
long size = 0;
size += url.length();
long s0 = System.currentTimeMillis();
long s2 = 0;
InputStream is = null;
HttpClient client = getHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse response = null;
String result = "";
try {
if (param != null) {
post.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
// // 将JSON进行UTF-8编码,以便传输中文
// String encoderJson = URLEncoder.encode(param, HTTP.UTF_8);
// StringEntity se = new StringEntity(encoderJson);
// 解决中文乱码问题
StringEntity se = new StringEntity(param.toString(), HTTP.UTF_8);
se.setContentType(CONTENT_TYPE_TEXT_JSON);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
post.setEntity(se);
}
long s1 = System.currentTimeMillis();
response = client.execute(post);
HttpEntity entity = response.getEntity();
s2 = System.currentTimeMillis();
if (entity != null) {
// start 读取整个页面内容
is = entity.getContent();
// end 读取整个页面内容
result = readResponseInStream(is);
}
} finally {
try {
closeIOConnection(is, null, null);
closeHttpConnection((CloseableHttpResponse) response, (DefaultHttpClient) client, null, post, null);
} catch (Exception e) {
// //e.printStackTrace();
logger.error("关闭请求资源异常" + e);
}
}
long s3 = System.currentTimeMillis();
return result;
}
public static void closeHttpConnection(CloseableHttpResponse response, DefaultHttpClient client, HttpGet get, HttpPost post, HttpPut put) throws IOException{
if (response != null) {
response.close();
}
if (client != null) {
client.close();
}
if (get != null) {
get.releaseConnection();
}
if (post != null) {
post.releaseConnection();
}
if (put != null) {
put.releaseConnection();
}
}
public static void closeIOConnection(InputStream in, OutputStream out, Reader reader) throws IOException{
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (reader != null) {
reader.close();
}
}
public static void closeURLConnection(HttpURLConnection connection) {
if (connection != null) {
connection.disconnect();
}
}
}
package com.spacetech.common.utils;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.spacetech.common.exception.ExceptionUtil;
public class JsonUtil {
private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);
public static String formatJsonResult(String api, Object obj, String returnCode, String returnMsg, String version) {
JSONObject result = new JSONObject();
result.put("api", api);
result.put("data", obj);
result.put("v", version);
try {
result.put("ret", formatReturnMsg(returnCode, returnMsg));
return JSON.toJSONString(result, SerializerFeature.WriteMapNullValue,
SerializerFeature.DisableCircularReferenceDetect).replace(" ", " ");
} catch (Exception e) {
// TODO: handle exception
result = new JSONObject();
result.put("api", api);
result.put("v", version);
result.put("ret", formatReturnMsg(returnCode, "系统数据转换发生异常,请联系管理员"));
return JSON.toJSONString(result, SerializerFeature.WriteMapNullValue,
SerializerFeature.DisableCircularReferenceDetect).replace(" ", " ");
}
}
public static JSONObject formatReturnMsg(String code, String msg) {
JSONObject result = new JSONObject();
result.put("code", code);
if (ApiUtil.ERROR_INTERNAL_SERVER.equals(code)) {
msg = ExceptionUtil.transformDbException(msg);
}
result.put("msg", msg);
return result;
}
public static JSONObject formatJSONObject(String json) {
JSONObject resultJson = JSONObject.parseObject(json);
ApiUtil.verifyResponse(resultJson);
return JSONObject.parseObject(resultJson.getString("data"));
}
public static List<JSONObject> formatJSONArray(String json) {
JSONObject resultJson = JSONObject.parseObject(json);
ApiUtil.verifyResponse(resultJson);
return JSONObject.parseArray(resultJson.getString("data"), JSONObject.class);
}
public static String formatNullStr(String json) {
JSONObject resultJson = JSONObject.parseObject(json);
return StringUtil.getNullStr(resultJson.getString("data"));
}
}
package com.spacetech.common.utils;
import java.security.MessageDigest;
public class MD5Util {
private static MessageDigest md5;
private static MessageDigest getMd5() {
if (md5 == null) {
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return md5;
}
/**
* Title: MD5加密 生成32位md5码
* Description: TestDemo
* @author lu
* @date 2016年6月23日 下午2:36:07
* @param inStr
* @return 返回32位md5码
* @throws Exception
*/
public static String md5Encode(String inStr) throws Exception {
MessageDigest md5 = getMd5();
byte[] byteArray = inStr.getBytes("UTF-8");
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* Title: MD5加密
* Description: TestDemo
* @author lu
* @date 2016年6月23日 下午2:43:31
* @param inStr
* @return
*/
public static String string2MD5(String inStr) {
MessageDigest md5 = getMd5();
char[] charArray = inStr.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* Title: 加密解密算法 执行一次加密,两次解密
* Description: TestDemo
* @author lu
* @date 2016年6月23日 下午2:37:29
* @param inStr
* @return
*/
public static String convertMD5(String inStr) {
char[] a = inStr.toCharArray();
for (int i = 0; i < a.length; i++) {
a[i] = (char) (a[i] ^ 't');
}
String s = new String(a);
return s;
}
public static String md5Decode(String str) {
String result = convertMD5(convertMD5(str));
return result;
}
public static void main(String[] args) {
String s = new String("tangfuqiang");
System.out.println("原始:" + s);
System.out.println("MD5后:" + string2MD5(s));
System.out.println("加密的:" + convertMD5(s));
String result = string2MD5(s);
System.out.println("result加密的:" + result);
System.out.println("解密的:" + convertMD5(result));
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
}
package com.spacetech.common.utils;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class NacosUtil {
private static final Logger log = LoggerFactory.getLogger(NacosUtil.class);
private static final String GROUP = "COMMON_GROUP";
private static String dataId = "util.properties";
private static String nacosServerAddr = "10.10.10.221:8848";
private static Map<String, String> properties;
static {
try {
if (StringUtil.isNotEmpty(System.getProperty("nacosServerAddr"))) {
nacosServerAddr = System.getProperty("nacosServerAddr");
}
if (StringUtil.isNotEmpty(System.getProperty("dataId"))) {
dataId = System.getProperty("dataId");
}
ConfigService configService = NacosFactory.createConfigService(nacosServerAddr);
String config = configService.getConfig(dataId, GROUP, 3000);
transforProperty(config);
//添加监听
configService.addListener(dataId, GROUP, new Listener() {
@Override
public Executor getExecutor() {
return new ThreadPoolExecutor(2,4,10, TimeUnit.SECONDS,new LinkedBlockingDeque<>(100), Executors.defaultThreadFactory());
}
@Override
public void receiveConfigInfo(String configInfo) {
transforProperty(configInfo);
}
});
} catch (NacosException e) {
log.error("获取配置文件{}出错===={},{}", dataId,e.getMessage(),e);
}
}
/**
* 获取配置
* @param key
* @return
*/
public static String getConfig(String key) {
return properties.get(key);
}
/**
* 将nacos拉取的配置串解析成properties
* @param configStr
*/
private static void transforProperty(String configStr){
try {
String[] split = configStr.split("\n");
properties = Stream.of(split).filter(value -> StringUtil.isNotEmpty(value) && !value.startsWith("#"))
.collect(Collectors.toMap(value -> value.substring(0, value.indexOf("=")).trim(),
value -> value.substring(value.indexOf("=") + 1).trim(),
(a, b) -> a));
} catch (Exception e) {
log.error("解析配置文件出错,请检查格式", e.getMessage(), e);
}
}
}
package com.spacetech.common.utils;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
public class NetUtil {
/**
* 获得主机IP
*
* @return String
*/
public static boolean isWindowsOS() {
boolean isWindowsOS = false;
String osName = System.getProperty("os.name");
if (osName.toLowerCase().indexOf("windows") > -1) {
isWindowsOS = true;
}
return isWindowsOS;
}
/**
* 获取本机ip地址,并自动区分Windows还是linux操作系统
*
* @return String
*/
public static String getIpAddr() {
try {
String sIP = "";
InetAddress ip = null;
// 如果是Windows操作系统
if (isWindowsOS()) {
ip = InetAddress.getLocalHost();
}
// 如果是Linux操作系统
else {
boolean bFindIP = false;
Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
if (bFindIP) {
break;
}
NetworkInterface ni = (NetworkInterface) netInterfaces
.nextElement();
// ----------特定情况,可以考虑用ni.getName判断
// 遍历所有ip
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
ip = (InetAddress) ips.nextElement();
if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() // 127.开头的都是lookback地址
&& ip.getHostAddress().indexOf(":") == -1) {
bFindIP = true;
break;
}
}
}
}
if (null != ip) {
sIP = ip.getHostAddress();
}
return sIP;
} catch (Exception e) {
return "";
}
}
}
package com.spacetech.common.utils;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyun.oss.model.PutObjectResult;
import com.spacetech.common.exception.FilePutErrorException;
@Component
@Transactional(readOnly = true)
public class OSSClientUtil {
public static final String[] audioFileTypes = new String[] { "mp3", "wav", "wma", "mid", "m4a" };
public static final String[] videoFileTypes = new String[] { "asx", "asf", "mpg", "wmv", "3gp", "mov", "avi", "flv",
"mp4" };
public static final String[] imageFileTypes = new String[] { "jpg", "gif", "png", "webp", "bmp", "tiff" };
public static final String[] OSSimageFileTypes = new String[] { "jpg", "webp", "png", "bmp" };
public static final String[] OSSOfficeFileTypes = new String[] { "doc", "docx", "wps", "pdf", "xls", "xlsx", "pptx",
"ppt" };
public static String ALI_AK = "0DJchGp6j9IuK8iN";
public static String ALI_SK = "";
public static String BUCKET_NAME = "weixt-static";
public static final String SQXY_BUCKET_NAME = "weixt-sqxy";
public static String OFFICE_BUCKET_NAME = "weixt-office";
public static final String BUCKET_NAME_EXPORT = "weixt-export";
private static String ENDPOINT_INTERNAL = "http://oss-cn-qingdao-internal.aliyuncs.com";
public static String ENDPOINT = "http://oss-cn-qingdao.aliyuncs.com";
public static String ALI_IMAGE_URL = "https://static.weixiaotong.com.cn/";
public static String ALI_IMAGE_URL_HTPPS = "https://static.weixiaotong.com.cn/";
public static final String SQXY_IMAGE_URL = "http://sqxystatic.weixiaotong.com.cn/";
public static final String SQXY_COMMON_URL = "http://weixt-sqxy.oss-cn-qingdao.aliyuncs.com/";
public static String ALI_BUCKET_URL = "https://static.weixiaotong.com.cn";
public static final String ALI_COMMON_URL = "http://weixt-static.oss-cn-qingdao.aliyuncs.com/";
public static final String ALI_EXPORT_WEIXT_URL = "https://weixt-export.weixiaotong.com.cn/";
public static final String ALI_OFFICE_URL_HTPPS = "https://weixtoffice.weixiaotong.com.cn/";
public static final String ALI_OFFICEBUCKET_URL = "https://weixtoffice.weixiaotong.com.cn";
// office存储外网
private static String OFFICE_ENDPOINT_INTERNAL = "http://oss-cn-hangzhou.aliyuncs.com";
public static final List<String> OSS_BUCKET_DOMAIN;
public static final String OSS_INTERNALBUCKET_DOMAIN;
static {
String data = NacosUtil.getConfig("oss_bucket_domain");
OSS_BUCKET_DOMAIN = (data == null) ? new ArrayList<>(0) : StringUtil.getNullStrToStringList(data);
OSS_INTERNALBUCKET_DOMAIN = NacosUtil.getConfig("oss_internalbucket_domain");
}
// 在上传到服务器的时候,是否在本地服务器也保存一份
public static Boolean saveLocalFile = false;
public static String localFileDic = "";
private static Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);
private static OSSClient getOSSClient(Boolean internal, String bucket_name) {
if (StringUtil.isNotEmpty(bucket_name) && OFFICE_BUCKET_NAME.equals(bucket_name)) {
return new OSSClient(OFFICE_ENDPOINT_INTERNAL, ALI_AK, ALI_SK);
}
if (internal) {
return new OSSClient(ENDPOINT_INTERNAL, ALI_AK, ALI_SK);
} else {
return new OSSClient(ENDPOINT, ALI_AK, ALI_SK);
}
}
/**
* 更加安全的获取TOKEN的方法
*
* @return
*/
private static OSSClient getSafeOSSClient(String bucketName) {
JSONObject bucketStsToken = getSafeOSSClientJson(bucketName);
if (bucketStsToken == null) {
return new OSSClient(ENDPOINT, ALI_AK, ALI_SK);
}
String accessKeyId = bucketStsToken.getString("accessKeyId");
String accessKeySecret = bucketStsToken.getString("accessKeySecret");
String stsToken = bucketStsToken.getString("stsToken");
String endpoint = bucketStsToken.getString("endpoint");
OSSClient result = new OSSClient(endpoint, accessKeyId, accessKeySecret, stsToken,
new ClientConfiguration().setSupportCname(false));
logger.info("getSafeOSSClient[" + bucketName + "] ststoken success!");
return result;
}
public static JSONObject getSafeOSSClientJson(String bucketName) {
long time0 = System.currentTimeMillis();
String endpoint = "";
if (StringUtil.isNotEmpty(bucketName) && OFFICE_BUCKET_NAME.equals(bucketName)) {
endpoint = OFFICE_ENDPOINT_INTERNAL;
} else {
endpoint = NacosUtil.getConfig("oss_endpoint");
}
String ossStsToken = NacosUtil.getConfig("oss_sts_token");
long time1 = System.currentTimeMillis();
logger.info("GET ZK CONFIG TIME=" + (time1 - time0));
JSONObject stsTokenJson = JSON.parseObject(ossStsToken);
if (stsTokenJson == null) {
return null;
}
JSONObject bucketStsToken = stsTokenJson.getJSONObject("put-" + bucketName);
String accessKeyId = bucketStsToken.getString("accessKeyId");
String accessKeySecret = bucketStsToken.getString("accessKeySecret");
String stsToken = bucketStsToken.getString("stsToken");
logger.info("getSafeOSSClient[" + bucketName + "] ststoken success!");
JSONObject result = new JSONObject();
result.put("accessKeyId", accessKeyId);
result.put("accessKeySecret", accessKeySecret);
result.put("stsToken", stsToken);
result.put("bucketName", bucketName);
result.put("endpoint", endpoint);
return result;
}
/*public static void updateZkStsToken(JSONObject _stsToken) {
zkUtil.setData(ConfigUpdater.PATH + "/oss_sts_token", _stsToken.toJSONString());
}*/
public static void initOSSClientParam(String endpoint, String ali_ak, String ali_sk) {
if (StringUtil.isNotEmpty(endpoint) && StringUtil.isNotEmpty(ali_ak)) {
ENDPOINT = endpoint;
ALI_AK = ali_ak;
ALI_SK = ali_sk;
} else {
logger.warn("OSS配置有误endpoint=" + endpoint + " ali_sk=" + ali_sk);
}
}
/**
* /** 通过文件名读取文件,并提交到阿里OSS上,上传文件后将原始文件删除。
*
* @param filename
* @param compressFlag
* @param internal
* @param saveLocalfile 存储在本地服务,不删除
* @param saveLocalfilegetOSSClient 存储在本地服务,不删除
* @return 阿里OSS上的文件名
* @throws Exception
*/
public static String putFile(String filename, Boolean compressFlag, boolean internal, boolean saveLocalfile,
String localfileInternet) {
logger.info("put qiniu filename=" + filename + " saveLocalfile=" + saveLocalfile + " localfileInternet="
+ localfileInternet + " internal=" + internal);
String filetype = FileUtil.getFileType(filename);
if (filetype != null) {
filetype = filetype.toLowerCase();
if (filetype.equals("jpeg")) {
filetype = "jpg";
}
}
String result = "";
try {
String filekey = getFileSha1Key(filename, filetype);
if (isVideo(filetype) && compressFlag) {
String mp4file = FfmpegUtil.encodeToMp4Video(filename, filekey);
// mp4Url = ALI_IMAGE_URL + putOSSFile(mp4file, BUCKET_NAME, internal);
result = mp4file;
// } else if (getFileTypeIsOSSImageSupport(filetype)) {
//
// result = ALI_IMAGE_URL + putOSSFile(filename, BUCKET_NAME, internal);
} else {
result = filename;
// result = ALI_IMAGE_URL + putOSSFile(filename, BUCKET_NAME, internal);
}
if (saveLocalfile) {
String filehashkey = FileHashUtil.getSHA1Checksum(result) + "." + filetype;
if (StringUtil.isNullOrEmpty(filehashkey)) {
throw new FilePutErrorException("result:" + result);
}
FileUtil.renameFile(filename, filehashkey);
return localfileInternet + filehashkey;
} else {
result = getAliUrl(putOSSFile(result, BUCKET_NAME, internal));
if (StringUtil.isNotEmpty(result)) {
cleanFiles(filename, filekey);
return result;
} else {
logger.error("图片上传错误" + result + " filename=" + filename);
throw new FilePutErrorException("result:" + result);
}
}
} catch (Exception e) {
logger.error("图片上传错误" + result + " filename=" + filename, e);
return "";
}
}
private static String getAliUrl(String fileName) {
return ALI_IMAGE_URL + "/" + fileName;
}
/**
* 不上传文件,仅仅获取截屏和时间
*
* @param filename
* @return 阿里OSS上的文件名
*/
public static JSONObject getThumbnailAndPlayTime(String filename, Boolean compressFlag, String startTime,
String cdnUrl, String bucketName, boolean internal) throws Exception {
String filetype = FileUtil.getFileType(filename);
String filekey = getFileSha1Key(filename, filetype);
JSONObject result = new JSONObject();
if (isVideo(filetype)) {
result.put("time", FfmpegUtil.getVideoTime(filename));
result.put("picUrl", getVideoThumbnail(filename, startTime, cdnUrl, bucketName, filekey, internal));
} else if (getFileTypeIsOSSImageSupport(filetype)) {
result.put("picUrl", cdnUrl + putOSSFile(filename, bucketName, internal));
logger.info("转码并上传成功:" + result.getString("picUrl"));
} else {
throw new FilePutErrorException("文件格式有误!");
}
if (!result.isEmpty()) {
cleanFiles(filename, filekey);
logger.info("清理临时文件");
return result;
} else {
throw new FilePutErrorException("转码失败!");
}
}
/**
* 通过文件名读取文件,并提交到阿里OSS上,上传文件后将原始文件删除。
*
* @param filename
* @return 阿里OSS上的文件名
*/
public static Map putFileAndGetThumbnail(String filename, Boolean compressFlag, String startTime, String cdnUrl,
String bucketName, boolean internal) throws Exception {
logger.info("put qiniu filename=" + filename);
String filetype = FileUtil.getFileType(filename);
if (filetype != null) {
filetype = filetype.toLowerCase();
if (filetype.equals("jpeg")) {
filetype = "jpg";
}
}
String filekey = getFileSha1Key(filename, filetype);
Map<String, String> result = new HashMap<String, String>();
// 存储文件到本地
result.put("filetype", filetype);
if (isVideo(filetype)) {
result.put("url", getOssFileName(filename, compressFlag, cdnUrl, bucketName, filekey, internal));
result.put("picUrl", getVideoThumbnail(filename, startTime, cdnUrl, bucketName, filekey, internal));
} else if (getFileTypeIsOSSImageSupport(filetype)) {
String url = cdnUrl + putOSSFile(filename, bucketName, internal);
result.put("url", url);
result.put("picUrl", url);
} else {
throw new FilePutErrorException("文件格式有误!");
}
if (!result.isEmpty()) {
cleanFiles(filename, filekey);
return result;
} else {
throw new FilePutErrorException("转码失败!");
}
}
private static String getFileSha1Key(String filename, String filetype) throws Exception {
return FileHashUtil.getSHA1Checksum(filename) + System.currentTimeMillis() + "." + filetype;
}
/**
* 获取截屏,并上传到CDN,返回文件路径
*
* @param filename
* @param startTime
* @param cdnUrl
* @param bucketName
* @param filekey
* @return
* @throws InterruptedException
* @throws Exception
*/
private static String getVideoThumbnail(String filename, String startTime, String cdnUrl, String bucketName,
String filekey, boolean internal) throws InterruptedException, Exception {
String picUrl = "";
String makeImgbyvideoFilename = FfmpegUtil.makeImgbyvideo(filename, filekey, "", startTime);
if (StringUtil.isNotEmpty(makeImgbyvideoFilename)) {
File imagefile = new File(makeImgbyvideoFilename);
if (!imagefile.exists()) {
Thread.sleep(500);
}
if (imagefile.exists()) {
picUrl = cdnUrl + putOSSFile(makeImgbyvideoFilename, bucketName, internal);
} else {
picUrl = "";
logger.error("获取缩略图失败:" + makeImgbyvideoFilename);
}
} else {
picUrl = "";
}
return picUrl;
}
private static String getOssFileName(String filename, Boolean compressFlag, String cdnUrl, String bucketName,
String filekey, boolean internal) throws Exception {
if (compressFlag) {
String mp4file = FfmpegUtil.encodeToMp4Video(filename, filekey);
return cdnUrl + putOSSFile(mp4file, bucketName, internal);
} else {
return cdnUrl + putOSSFile(filename, bucketName, internal);
}
}
/**
* 上传图片和视频文件到阿里云 视频文件将进行截图
*
* @param filename
* @param compressFlag
* @param
* @param
* @param internal
* @return
* @throws Exception picUrl:封面 url:阿里云文件地址
*/
public static Map putFileHaveThumbnail(String filename, Boolean compressFlag, boolean internal,
Boolean saveLocalfile, String localfileInternet, String widthAndHeigth) throws Exception {
// String cdnUrl = ALI_IMAGE_URL_HTPPS;
// return putFileAndThumbnail(filename, compressFlag, cdnUrl, BUCKET_NAME,
// internal, widthAndHeigth);
String filetype = FileUtil.getFileType(filename);
if (isFileTypeIsOSSOffice(filetype)) {
return putFileAndThumbnail(filename, compressFlag, ALI_OFFICE_URL_HTPPS, OFFICE_BUCKET_NAME, internal,
widthAndHeigth);
} else {
return putFileAndThumbnail(filename, compressFlag, getAliUrl(), BUCKET_NAME, internal, widthAndHeigth);
}
}
private static String getAliUrl() {
return StringUtil.isNotEmpty(ALI_IMAGE_URL_HTPPS) && ALI_IMAGE_URL_HTPPS.lastIndexOf("/") > 15
? ALI_IMAGE_URL_HTPPS
: (ALI_IMAGE_URL_HTPPS + "/");
}
public static String getOssHttpUrlDomain(String ossHttpUrlDomain) {
return StringUtil.isNotEmpty(ossHttpUrlDomain) && ossHttpUrlDomain.lastIndexOf("/") > 15 ? ossHttpUrlDomain
: (ossHttpUrlDomain + "/");
}
/**
* 上传图片和视频文件到阿里云 视频文件将进行截图
*
* @param filename
* @param
* @param
* @param
* @param internal
* @return
* @throws Exception picUrl:封面 url:阿里云文件地址
*/
public static String putNotWxtFile(String filename, boolean internal, String widthAndHeigth) throws Exception {
String filetype = FileUtil.getFileType(filename);
if (isFileTypeIsOSSOffice(filetype)) {
return StringUtil.getNullStr(putFileAndThumbnail(filename, false, ALI_OFFICE_URL_HTPPS, OFFICE_BUCKET_NAME,
internal, widthAndHeigth).get("url"));
} else {
return StringUtil
.getNullStr(putFileAndThumbnail(filename, false, getAliUrl(), BUCKET_NAME, internal, widthAndHeigth)
.get("url"));
}
}
public static Map putOfficeFileHaveThumbnail(String filename, Boolean compressFlag, boolean internal,
Boolean saveLocalfile, String localfileInternet, String widthAndHeigth) throws Exception {
String filetype = FileUtil.getFileType(filename);
if (isFileTypeIsOSSOffice(filetype)) {
return putFileAndThumbnail(filename, compressFlag, ALI_OFFICE_URL_HTPPS, OFFICE_BUCKET_NAME, internal,
widthAndHeigth);
} else {
return putFileAndThumbnail(filename, compressFlag, getAliUrl(), BUCKET_NAME, internal, widthAndHeigth);
}
}
/**
* 通过文件名读取文件,并提交到阿里OSS上,上传文件后将原始文件删除。
*
* @param filename
* @return 阿里OSS上的文件名
*/
public static Map putFileAndThumbnail(String filename, Boolean compressFlag, String cdnUrl, String bucketName,
boolean internal, String widthAndHeigth) throws Exception {
logger.info("put qiniu putFileAndThumbnail=" + filename);
String filetype = FileUtil.getFileType(filename);
if (filetype != null) {
filetype = filetype.toLowerCase();
if (filetype.equals("jpeg")) {
filetype = "jpg";
}
}
String filekey = getFileSha1Key(filename, filetype);
String mp4Url = "";
Map<String, String> result = new HashMap<String, String>();
// 存储文件到本地
result.put("filetype", filetype);
if (isVideo(filetype)) {
Map<String, String> movieInfo = FfmpegUtil.getMovieInfo(filename);
String makeImgbyvideoFilename = FfmpegUtil.makeImgbyvideo(filename, filekey, widthAndHeigth, movieInfo);
result.put("duration", FfmpegUtil.getTimelen(movieInfo.get("Duration")) + "");
if (compressFlag) {
String mp4file = FfmpegUtil.encodeToMp4Video(filename, filekey);
mp4Url = cdnUrl + putOSSFile(mp4file, bucketName, internal);
result.put("url", mp4Url);
} else {
result.put("url", cdnUrl + putOSSFile(filename, bucketName, internal));
}
if (StringUtil.isNotEmpty(makeImgbyvideoFilename)) {
File imagefile = new File(makeImgbyvideoFilename);
if (!imagefile.exists()) {
Thread.sleep(500);
}
if (imagefile.exists()) {
result.put("picUrl", cdnUrl + putOSSFile(makeImgbyvideoFilename, bucketName, internal));
} else {
result.put("picUrl", "");
logger.error("获取缩略图失败:" + makeImgbyvideoFilename);
}
} else {
result.put("picUrl", "");
}
} else if (getFileTypeIsOSSImageSupport(filetype)) {
String url = cdnUrl + putOSSFile(filename, bucketName, internal);
result.put("url", url);
result.put("picUrl", url);
} else {
logger.warn("put qiniu putFileAndThumbnail=" + filename + " filetype=" + filetype);
String url = cdnUrl + putOSSFile(filename, bucketName, internal);
result.put("url", url);
result.put("picUrl", url);
}
if (!result.isEmpty()) {
cleanFiles(filename, filekey);
return result;
} else {
throw new FilePutErrorException("上传失败!");
}
}
/**
* 通过文件名读取文件,并提交到阿里OSS上,上传文件后将原始文件删除。
*
* @param filename
* @return 阿里OSS上的文件名
*/
public static Map putFileAndThumbnailNotPic(String filename, Boolean compressFlag, String cdnUrl, String bucketName,
boolean internal) throws Exception {
logger.info("put qiniu filename=" + filename);
String filetype = FileUtil.getFileType(filename);
String filekey = getFileSha1Key(filename, filetype);
String mp4Url = "";
Map<String, String> result = new HashMap<String, String>();
if (isVideo(filetype)) {
if (compressFlag) {
logger.info("in video file :" + filename + " compressFlag=" + compressFlag);
String mp4file = FfmpegUtil.encodeToMp4Video(filename, filekey);
logger.info("after encodeToMp4Video file :" + mp4file);
mp4Url = cdnUrl + putOSSFile(mp4file, bucketName, internal);
logger.info("after encodeToMp4Video url :" + mp4Url);
result.put("url", mp4Url);
} else {
result.put("url", cdnUrl + putOSSFile(filename, bucketName, internal));
}
} else {
throw new FilePutErrorException("文件格式有误!");
}
if (!result.isEmpty()) {
cleanFiles(filename, filekey);
return result;
} else {
throw new FilePutErrorException("转码失败!");
}
}
/**
* 判断是否属于视频阿里OSS图片处理支持的格式
*
* @param fileType
* @return
*/
public static boolean getFileTypeIsOSSImageSupport(String fileType) {
return Arrays.<String>asList(imageFileTypes).contains(fileType);
}
/**
* 判断是否office文档
*
* @param fileType
* @return
*/
public static boolean isFileTypeIsOSSOffice(String fileType) {
return Arrays.<String>asList(OSSOfficeFileTypes).contains(fileType);
}
private static void cleanFiles(String filename, String filekey) {
long time = System.currentTimeMillis();
FileUtil.delDiskFile(null, filename);
FileUtil.delDiskFile(FfmpegUtil.TEMPPATH, filekey + ".HD.flv");
FileUtil.delDiskFile(FfmpegUtil.TEMPPATH, filekey + ".HD.mp4");
FileUtil.delDiskFile(FfmpegUtil.TEMPPATH, filekey + ".bmp");
}
/**
* 判断是否属于视频mp3
*
* @param fileType
* @return
*/
public static boolean isVideo(String fileType) {
boolean isVideo = Arrays.<String>asList(videoFileTypes).contains(fileType);
return isVideo;
}
public static String putOSSFile(String filename, String bucket_name, boolean internal) throws Exception {
String filetype = getFileType(filename);
if (filetype != null) {
filetype = filetype.toLowerCase();
if (filetype.equals("jpeg")) {
filetype = "jpg";
}
}
String filekey = FileHashUtil.getSHA1Checksum(filename) + "." + filetype;
saveLocalFile(filename, filekey);
OSSClient client = getSafeOSSClient(bucket_name);
Object object = getFileInfo(client, filekey, bucket_name);
if (object != null) {
client.shutdown();
return filekey;
}
logger.info("oss file not exists:" + filekey + " filename=" + filename);
InputStream content = null;
// 初始化OSSClient
try {
// 获取指定文件的输入流
File file = new File(filename);
content = new FileInputStream(file);
// 创建上传Object的Metadata
ObjectMetadata meta = new ObjectMetadata();
// 必须设置ContentLength
meta.setContentLength(file.length());
// 上传Object.
client.putObject(bucket_name, filekey, content, meta);
// 打印ETag
// 上传以后删除文件
// file.delete();
logger.info("---------SAFE-OSS---------文件上传成功,远程文件名:" + filekey + " 本地文件名:" + filename + " 文件大小:"
+ file.length() / 1024 + "k");
return filekey;
} catch (Exception e) {
logger.error("文件上传失败,错误原因:filename=" + filename, e);
throw new RuntimeException("文件上传失败,错误原因:" + e.getMessage());
} finally {
client.shutdown();
if (content != null) {
content.close();
}
}
}
/**
* 获取文件类型 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
*
* @param fileName
* @return
*/
public static String getFileType(String fileName) {
// 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
public static void saveLocalFile(String filename, String hashfilename) {
try {
if (saveLocalFile) {
copyByChannel(filename, localFileDic + "/" + hashfilename);
}
} catch (Exception e) {
e.printStackTrace();
logger.error("存储本地文件出错", e);
}
}
/**
* 通过文件的HASH值获取阿里OSS文件信息
*
* @return
* @return
* @throws Exception
*/
public static OSSObject getFileInfo(OSSClient client, String key, String bucket_name) throws IOException {
// 初始化OSSClient
OSSObject result = null;
try {
// 获取Object,返回结果为OSSObject对象
result = client.getObject(bucket_name, key);
} catch (Exception e) {
}
return result;
}
public static void copyByChannel(String sourceFileName, String targgetFileName) {
File sourceFile = new File(sourceFileName);
File targgetFile = new File(targgetFileName);
if (!sourceFile.exists()) {
logger.error("源文件不存在!");
return;
}
if (targgetFile.exists()) {
logger.info("文件已经存在!");
return;
}
int length = 2097152;
FileInputStream in = null;
FileOutputStream out = null;
FileChannel inC = null, outC = null;
try {
in = new FileInputStream(sourceFile);
out = new FileOutputStream(targgetFile);
inC = in.getChannel();
outC = out.getChannel();
ByteBuffer b = null;
while (true) {
if (inC.position() == inC.size()) {
return;
}
if ((inC.size() - inC.position()) < length) {
length = (int) (inC.size() - inC.position());
} else
length = 2097152;
b = ByteBuffer.allocateDirect(length);
inC.read(b);
b.flip();
outC.write(b);
outC.force(false);
}
} catch (Exception e) {
logger.error("copy file error,", e);
} finally {
try {
if (inC != null) {
inC.close();
}
if (outC != null) {
outC.close();
}
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
logger.error("close file error,", e);
}
}
}
public static String getSotreFilePath(String filePath) {
String localfileDic = "";
if (StringUtil.isNullOrEmpty(filePath)) {
localfileDic = UtilConstant.WEIKE_FILE;
} else {
localfileDic = filePath;
}
FileUtil.makeDir(localfileDic);
return localfileDic;
}
public static String putBase64File(String basePath, String realPath, boolean internal, Boolean saveLocalfile,
String localfileInternet) {
// String storeFilePath = FileUtil.getStoreFilePath(realPath, "/temp");
String filePath = "";
try {
filePath = FileUtil.fileUploadNews(basePath, getSotreFilePath(realPath));
filePath = OSSClientUtil.putFile(filePath, true, internal, saveLocalfile, localfileInternet);
} catch (Exception e) {
e.printStackTrace();
}
return filePath;
}
/**
* 通过文件名读取文件(主要针对用户需要导出),并提交到阿里OSS上,上传文件后将原始文件删除。 注意:本方法将使用原始文件名,而不是hash过的文件名
*
* @param filename
* @return 阿里OSS上的文件名
*/
public static String putExportFileWithOrignName(String filename, boolean internal) throws Exception {
String filekey = FileUtil.getOrignFileName(filename);
String result = ALI_EXPORT_WEIXT_URL + putOSSFileWithOrignFileName(filename, BUCKET_NAME_EXPORT, internal);
if (StringUtil.isNotEmpty(result)) {
cleanFiles(filename, filekey);
return result;
} else {
throw new FilePutErrorException("result:" + result);
}
}
public static String putExportFileWithOrignName(String filename, boolean internal, boolean saveLocalfile,
String localfileInternet) throws Exception {
String filekey = FileUtil.getOrignFileName(filename);
if (saveLocalfile) {
String result = localfileInternet + filekey;
return result;
} else {
String result = ALI_EXPORT_WEIXT_URL + putOSSFileWithOrignFileName(filename, BUCKET_NAME_EXPORT, internal);
if (StringUtil.isNotEmpty(result)) {
cleanFiles(filename, filekey);
return result;
} else {
throw new FilePutErrorException("result:" + result);
}
}
}
public static String putFileWithOrignName(String filename, boolean internal, boolean saveLocalfile,
String localfileInternet) throws Exception {
String filekey = FileUtil.getOrignFileName(filename);
if (saveLocalfile) {
String result = localfileInternet + filekey;
return result;
} else {
String result = getAliUrl() + putOSSFileWithOrignFileName(filename, BUCKET_NAME, internal);
if (StringUtil.isNotEmpty(result)) {
cleanFiles(filename, filekey);
return result;
} else {
throw new FilePutErrorException("result:" + result);
}
}
}
public static String putOSSFileWithOrignFileName(String filename, String bucket_name, boolean internal)
throws Exception {
String filetype = getFileType(filename);
if (filetype != null) {
filetype = filetype.toLowerCase();
if (filetype.equals("jpeg")) {
filetype = "jpg";
}
}
String filekey = FileUtil.getOrignFileName(filename);
OSSClient client = getSafeOSSClient(bucket_name);
Object object = getFileInfo(client, filekey, bucket_name);
if (object != null) {
client.shutdown();
return filekey;
}
try {
// 初始化OSSClient
// 获取指定文件的输入流
File file = new File(filename);
InputStream content = new FileInputStream(file);
// 创建上传Object的Metadata
ObjectMetadata meta = new ObjectMetadata();
// 必须设置ContentLength
meta.setContentLength(file.length());
// 上传Object.
PutObjectResult result = client.putObject(bucket_name, filekey, content, meta);
// 打印ETag
// 上传以后删除文件
// file.delete();
logger.info("文件上传成功,远程文件名:" + filekey + " 本地文件名:" + filename + " 文件大小:" + file.length() / 1024 + "k"
+ " tag=" + result.getETag());
} catch (Exception e) {
e.printStackTrace();
} finally {
client.shutdown();
}
return filekey;
}
/**
* 获取通过前端页面直接上传阿里云oss服务器的,相关签名和认证码
*
* @return
*/
public static Map<String, String> getOSSPolicyAndSignature(boolean internal, String bucketName) {
Map<String, String> resutlMap = new HashMap<String, String>();
OSSClient client = getOSSClient(internal, bucketName);
try {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, 30);// 有效期30分钟
PolicyConditions policyConditions = new PolicyConditions();
policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 104857600 * 3);
String policy = client.generatePostPolicy(calendar.getTime(), policyConditions);
String signature = client.calculatePostSignature(policy);
policy = new String(Base64.encodeBase64(policy.getBytes("UTF-8")));
resutlMap.put("policy", policy);
resutlMap.put("signature", signature);
resutlMap.put("OSSAccessKeyId", ALI_AK);
resutlMap.put("bucket", getBucketUrl(bucketName));
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取通过前端页面直接上传阿里云oss服务器的,相关签名和认证码 错误:" + e.getMessage(), e);
} finally {
client.shutdown();
}
return resutlMap;
}
private static String getBucketUrl(String bucketName) {
if (StringUtil.isNotEmpty(bucketName) && OFFICE_BUCKET_NAME.equals(bucketName)) {
return ALI_OFFICEBUCKET_URL;
} else {
return ALI_BUCKET_URL;
}
}
/**
* 替换外网为oss_internal_bucket所配置的内网文件地址
*
* @param path 需要替换的地址
* @return 替换后的地址
*/
public static String getInternalAddr(String path) {
for (String fileAddr : OSS_BUCKET_DOMAIN) {
if (path.contains(fileAddr)) {
return path.replace(fileAddr, OSS_INTERNALBUCKET_DOMAIN);
}
}
return path;
}
public static void main(String[] args) {
String a = "https://static.weixiaotong.com.cn";
System.out.println("333=" + getAliUrl());
System.out.println("333=" + a.substring(a.lastIndexOf("/"), a.lastIndexOf("/") + 1));
try {
long time1 = new Date().getTime();
String result = ALI_EXPORT_WEIXT_URL + putOSSFileWithOrignFileName("/mnt/work/dubbo/a.xls", BUCKET_NAME_EXPORT, false);
System.out.println("上传耗时:" + (new Date().getTime() - time1));
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.spacetech.common.utils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.NumberFormat;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public abstract class OutExcelMuSheetUtil {
public static final String EXPORT_PATH = "/export";
protected String fileName; // 文件名称
protected List<String> sheetNameList; // sheet名称
protected int rownum; // 列数
protected int sheetNum;
protected boolean isHasHeader;
public void fillExcel() {
OutputStream stream;
try {
stream = new FileOutputStream(fileName);
WritableWorkbook wbook;
wbook = Workbook.createWorkbook(stream);
for(int i = 0; i < sheetNum ; i++){
this.fillWorkbook(wbook,i);
}
wbook.write();
wbook.close();
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
private <T> void fillWorkbook(WritableWorkbook wbook,int index) {
try {
WritableSheet wsheet = wbook.createSheet(sheetNameList.get(index), index);
for (int i = 0; i < rownum + 2; i++) {// 设置每一列的宽度为20
wsheet.setColumnView(i, 20);
}
WritableFont wfont = new WritableFont(WritableFont.ARIAL, 18, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat wcfFC = new WritableCellFormat(wfont);
setHeaderCellStyle(wsheet, wcfFC);
wsheet.addCell(new Label(0, 0, sheetNameList.get(index), wcfFC)); // 设置标题
if(isHasHeader){
wcfFC = setTitleCellStyle(wcfFC);
fillHeaderData(wsheet, wcfFC);
}
wcfFC = setDataCellStyle(wcfFC);
fillCellData(wsheet, wcfFC);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setHeaderCellStyle(WritableSheet wsheet, WritableCellFormat wcfFC) {
try {
wcfFC.setBackground(Colour.WHITE);
wcfFC.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);
wcfFC.setAlignment(jxl.format.Alignment.CENTRE);
wsheet.mergeCells(0, 0, rownum, 0);
} catch (WriteException e) {
e.printStackTrace();
}
}
public WritableCellFormat setTitleCellStyle(WritableCellFormat wcfFC) {
try {
WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
wcfFC = new WritableCellFormat(wfont);
wcfFC.setBackground(Colour.YELLOW);
wcfFC.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);
wcfFC.setAlignment(jxl.format.Alignment.CENTRE);
wcfFC.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
wcfFC.setWrap(true);// 是否自动换行
} catch (WriteException e) {
e.printStackTrace();
}
return wcfFC;
}
public WritableCellFormat setDataCellStyle(WritableCellFormat wcfFC) {
try {
WritableFont wfont = new WritableFont(WritableFont.COURIER, 14, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
wcfFC = new WritableCellFormat(wfont, NumberFormats.TEXT);
wcfFC.setBackground(Colour.WHITE);
wcfFC.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);
wcfFC.setAlignment(jxl.format.Alignment.CENTRE);
} catch (WriteException e) {
e.printStackTrace();
}
return wcfFC;
}
public WritableCellFormat setErrorDataCellStyle(WritableCellFormat wcfFC) {
try {
WritableFont wfont = new WritableFont(WritableFont.COURIER, 14, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.RED);
wcfFC = new WritableCellFormat(wfont);
wcfFC.setBackground(Colour.WHITE);
wcfFC.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);
wcfFC.setAlignment(jxl.format.Alignment.CENTRE);
} catch (WriteException e) {
e.printStackTrace();
}
return wcfFC;
}
public abstract void fillHeaderData(WritableSheet wsheet, WritableCellFormat wcfFC);
public abstract void fillCellData(WritableSheet wsheet, WritableCellFormat wcfFC);
protected WritableCellFormat getNumberCellStyle(int fontsize) {
NumberFormat nf = new jxl.write.NumberFormat("0");
WritableCellFormat wcfN = new WritableCellFormat(nf);
try {
WritableFont wfont = new WritableFont(WritableFont.COURIER, fontsize, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
wcfN = new WritableCellFormat(wfont);
wcfN.setBackground(Colour.WHITE);
wcfN.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);
wcfN.setAlignment(jxl.format.Alignment.CENTRE);
} catch (WriteException e) {
e.printStackTrace();
}
return wcfN;
}
public WritableCellFormat getFloatCellStyle() {
WritableFont wfont = new WritableFont(WritableFont.COURIER, 14, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat wcfFN = new WritableCellFormat(wfont, NumberFormats.FLOAT);
try {
wcfFN.setBackground(Colour.WHITE);
wcfFN.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);
wcfFN.setAlignment(jxl.format.Alignment.CENTRE);
wcfFN.setVerticalAlignment(VerticalAlignment.CENTRE);
} catch (WriteException e) {
e.printStackTrace();
}
return wcfFN;
}
}
package com.spacetech.common.utils;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import jxl.Workbook;
import jxl.format.Border;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.NumberFormat;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public abstract class OutExcelUtil {
public static final String EXPORT_PATH = "/export";
protected String fileName; // 文件名称
protected String sheetName; // sheet名称
protected int rownum; // 列数
public void fillExcel() {
OutputStream stream;
try {
stream = new FileOutputStream(fileName);
WritableWorkbook wbook;
wbook = Workbook.createWorkbook(stream);
this.fillWorkbook(wbook);
wbook.write();
wbook.close();
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
private <T> void fillWorkbook(WritableWorkbook wbook) {
try {
WritableSheet wsheet = wbook.createSheet(sheetName, 0);
for (int i = 0; i < rownum + 2; i++) {// 设置每一列的宽度为20
wsheet.setColumnView(i, 20);
}
WritableFont wfont = new WritableFont(WritableFont.ARIAL, 18, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat wcfFC = new WritableCellFormat(wfont);
setHeaderCellStyle(wsheet, wcfFC);
wsheet.addCell(new Label(0, 0, sheetName, wcfFC)); // 设置标题
wcfFC = setTitleCellStyle(wcfFC);
fillHeaderData(wsheet, wcfFC);
wcfFC = setDataCellStyle(wcfFC);
fillCellData(wsheet, wcfFC);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setHeaderCellStyle(WritableSheet wsheet, WritableCellFormat wcfFC) {
try {
wcfFC.setBackground(Colour.WHITE);
wcfFC.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);
wcfFC.setAlignment(jxl.format.Alignment.CENTRE);
wcfFC.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
wsheet.mergeCells(0, 0, rownum, 0);
} catch (WriteException e) {
e.printStackTrace();
}
}
public WritableCellFormat setTitleCellStyle(WritableCellFormat wcfFC) {
try {
WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
wcfFC = new WritableCellFormat(wfont);
wcfFC.setBackground(Colour.YELLOW);
wcfFC.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);
wcfFC.setAlignment(jxl.format.Alignment.CENTRE);
wcfFC.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
wcfFC.setWrap(true);// 是否自动换行
} catch (WriteException e) {
e.printStackTrace();
}
return wcfFC;
}
public WritableCellFormat setDataCellStyle(WritableCellFormat wcfFC) {
try {
WritableFont wfont = new WritableFont(WritableFont.COURIER, 14, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
wcfFC = new WritableCellFormat(wfont, NumberFormats.TEXT);
wcfFC.setBackground(Colour.WHITE);
wcfFC.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);
wcfFC.setAlignment(jxl.format.Alignment.CENTRE);
wcfFC.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
} catch (WriteException e) {
e.printStackTrace();
}
return wcfFC;
}
public WritableCellFormat setErrorDataCellStyle(WritableCellFormat wcfFC) {
try {
WritableFont wfont = new WritableFont(WritableFont.COURIER, 14, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.RED);
wcfFC = new WritableCellFormat(wfont);
wcfFC.setBackground(Colour.WHITE);
wcfFC.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);
wcfFC.setAlignment(jxl.format.Alignment.CENTRE);
} catch (WriteException e) {
e.printStackTrace();
}
return wcfFC;
}
public abstract void fillHeaderData(WritableSheet wsheet, WritableCellFormat wcfFC);
public abstract void fillCellData(WritableSheet wsheet, WritableCellFormat wcfFC);
protected WritableCellFormat getNumberCellStyle(int fontsize) {
NumberFormat nf = new jxl.write.NumberFormat("0");
WritableCellFormat wcfN = new WritableCellFormat(nf);
try {
WritableFont wfont = new WritableFont(WritableFont.COURIER, fontsize, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
wcfN = new WritableCellFormat(wfont);
wcfN.setBackground(Colour.WHITE);
wcfN.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);
wcfN.setAlignment(jxl.format.Alignment.CENTRE);
} catch (WriteException e) {
e.printStackTrace();
}
return wcfN;
}
public WritableCellFormat getFloatCellStyle() {
WritableFont wfont = new WritableFont(WritableFont.COURIER, 14, WritableFont.NO_BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat wcfFN = new WritableCellFormat(wfont, NumberFormats.FLOAT);
try {
wcfFN.setBackground(Colour.WHITE);
wcfFN.setBorder(Border.ALL, jxl.format.BorderLineStyle.THIN);
wcfFN.setAlignment(jxl.format.Alignment.CENTRE);
wcfFN.setVerticalAlignment(VerticalAlignment.CENTRE);
} catch (WriteException e) {
e.printStackTrace();
}
return wcfFN;
}
}
package com.spacetech.common.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class ProcessBuilderUtil {
private static Logger logger = LoggerFactory.getLogger(ProcessBuilderUtil.class);
private static ProcessBuilder builder;
private static ProcessBuilder getProcessBuilder() {
if (builder == null) {
try {
builder = new ProcessBuilder();
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("执行脚本命令错误,错误原因:" + e.getMessage(), e);
}
}
return builder;
}
public static String callCommand(List<String> commandList) {
List<String> commend = new java.util.ArrayList<String>();
try {
StringBuffer result = new StringBuffer();
commend.add("curl");
commandList.add("-s");
commend.addAll(commandList);
logger.info("执行脚本命令" + commend.toString());
getProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
Process process = builder.start();
// 从输入流中读取视频信息
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
result.append(line);
}
int ret = process.waitFor();
return result.toString();
} catch (Exception e) {
logger.error("执行脚本命令错误,错误原因:" + e.getMessage() + " 命令集=" + commend.toString(), e);
return null;
}
}
/**
* 上传文件至腾讯
*
* @param postUrl
* @param fileLocalPath
* @return
*/
public static JSONObject callCommandPostFileToWechat(String postUrl, String fileLocalPath) {
List<String> commandList = new ArrayList<String>();
commandList.add(postUrl);
commandList.add("-F");
commandList.add("media=@" + fileLocalPath);
String commandResult = callCommand(commandList);
return JSON.parseObject(commandResult);
}
/**
* 上传文件至腾讯
*
* @param postUrl
* @param fileLocalPath
* @return
*/
public static JSONObject callCommandPostVideoFileToWechat(String postUrl, String fileLocalPath,
String description) {
List<String> commandList = new ArrayList<String>();
commandList.add("-F");
commandList.add("media=@" + fileLocalPath);
commandList.add("-F");
commandList.add("description=" + description + "");
commandList.add(postUrl);
String commandResult = callCommand(commandList);
logger.info("执行脚本命commandResult:" + commandResult);
return JSON.parseObject(commandResult);
}
/**
* 下载远程文件
*
* @param fileHttpUrl
* @return
*/
public static String callCommandDownFile(String fileHttpUrl, String fileLocalPath) {
List<String> commend = new ArrayList<String>();
try {
commend.add("curl");
commend.add("-o");
commend.add(fileLocalPath);
commend.add(fileHttpUrl);
getProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
Process process = builder.start();
int ret = process.waitFor();
} catch (Exception e) {
logger.error("执行脚本命令错误,错误原因:" + e.getMessage() + " 命令集=" + commend.toString(), e);
return null;
}
return fileLocalPath;
}
public static void main(String[] args) {
String accessToken = "9_Ya_jvwP-GXC6JZRF2QB7p8WB2wuGaPNEb_wYW-zybmyfe_3KMt1kKA8LMxfl5Ypx65OwZApfAQlF0RUppFdkZDOA2rkVfBZMvZU1j1hzWV8pHNVJV9us3_lmsNjX02zf3S4B-uUSbpqL8VjsCZCcAJAHEH";
String postUrl = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + accessToken
+ "&type=video";
String fileLocalPath = "/Users/hbz/Desktop/难得.mp4";
// callCommandPostFileToWechat(postUrl, fileLocalPath);
String fileHttpUrl = "http://mmbiz.qpic.cn/mmbiz_jpg/OBCkDJ0WaIv6zRQIDywgnVtoLMyWKx1bdY22NNrY8DvjTngZw8hFeQRsiaFtltDqyCwqQ5Z4BwdQkhGZVlIoaLg/0?wx_fmt=jpeg";
JSONObject description = new JSONObject();
description.put("title", "111");
description.put("introduction", "111");
JSONObject result = callCommandPostVideoFileToWechat(postUrl, "/Users/hbz/Desktop/难得.mp4",
description.toJSONString());
System.out.println(fileLocalPath + " result=" + result.toJSONString());
}
}
package com.spacetech.common.utils.QrUtil;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import com.google.zxing.common.BitMatrix;
public class MatrixToImageWriter {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private MatrixToImageWriter() {
}
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
public static void writeToFile(BitMatrix matrix, String format, File file)
throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format "
+ format + " to " + file);
}
}
public static void writeToStream(BitMatrix matrix, String format,
OutputStream stream) throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format "
+ format);
}
}
}
package com.spacetech.common.utils.QrUtil;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.spacetech.common.utils.FileUtil;
public class MatrixToImageWriterEx {
private static final MatrixToLogoImageConfig DEFAULT_CONFIG = new MatrixToLogoImageConfig();
/**
* 根据内容生成二维码数据
*
* @param content
* 二维码文字内容[为了信息安全性,一般都要先进行数据加密]
* @param width
* 二维码照片宽度
* @param height
* 二维码照片高度
* @return
*/
public static BitMatrix createQRCode(String content, int width, int height) {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
// 设置字符编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
BitMatrix matrix = null;
try {
matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
} catch (WriterException e) {
e.printStackTrace();
}
return matrix;
}
/**
* 写入二维码、以及将照片logo写入二维码中
*
* @param matrix
* 要写入的二维码
* @param format
* 二维码照片格式
* @param imagePath
* 二维码照片保存路径
* @param logoPath
* logo路径
* @throws IOException
*/
public static void writeToFile(BitMatrix matrix, String format, String imagePath, String logoPath)
throws IOException {
MatrixToImageWriter.writeToFile(matrix, format, new File(imagePath));
// 添加logo图片, 此处一定需要重新进行读取,而不能直接使用二维码的BufferedImage 对象
BufferedImage img = ImageIO.read(new File(imagePath));
MatrixToImageWriterEx.overlapImage(img, format, imagePath, logoPath, DEFAULT_CONFIG);
}
/**
* 写入二维码、以及将照片logo写入二维码中
*
* @param matrix
* 要写入的二维码
* @param format
* 二维码照片格式
* @param imagePath
* 二维码照片保存路径
* @param logoPath
* logo路径
* @param logoConfig
* logo配置对象
* @throws IOException
*/
public static Image writeToFile(BitMatrix matrix, String format, String imagePath, String logoPath,
MatrixToLogoImageConfig logoConfig) throws IOException {
MatrixToImageWriter.writeToFile(matrix, format, new File(imagePath));
// 添加logo图片, 此处一定需要重新进行读取,而不能直接使用二维码的BufferedImage 对象
BufferedImage img = ImageIO.read(new File(imagePath));
MatrixToImageWriterEx.overlapImage(img, format, imagePath, logoPath, logoConfig);
return img;
}
/**
* 将照片logo添加到二维码中间
*
* @param image
* 生成的二维码照片对象
* @param imagePath
* 照片保存路径
* @param logoPath
* logo照片路径
* @param formate
* 照片格式
*/
public static void overlapImage(BufferedImage image, String formate, String imagePath, String logoPath,
MatrixToLogoImageConfig logoConfig) {
try {
// BufferedImage logo = ImageIO.read(new File(logoPath));
BufferedImage logo = ImageIO.read(FileUtil.getInputStream(logoPath));
Graphics2D g = image.createGraphics();
// 考虑到logo照片贴到二维码中,建议大小不要超过二维码的1/5;
int width = image.getWidth() / logoConfig.getLogoPart();
int height = image.getHeight() / logoConfig.getLogoPart();
// logo起始位置,此目的是为logo居中显示
int x = (image.getWidth() - width) / 2;
int y = (image.getHeight() - height) / 2;
// 绘制图
g.drawImage(logo, x, y, width, height, null);
// 给logo画边框
// 构造一个具有指定线条宽度以及 cap 和 join 风格的默认值的实心 BasicStroke
g.setStroke(new BasicStroke(logoConfig.getBorder()));
g.setColor(logoConfig.getBorderColor());
g.drawRect(x, y, width, height);
g.dispose();
// 写入logo照片到二维码
ImageIO.write(image, formate, new File(imagePath));
} catch (Exception e) {
e.printStackTrace();
}
}
}
\ No newline at end of file
package com.spacetech.common.utils.QrUtil;
import java.awt.Color;
public class MatrixToLogoImageConfig {
// logo默认边框颜色
public static final Color DEFAULT_BORDERCOLOR = Color.RED;
// logo默认边框宽度
public static final int DEFAULT_BORDER = 2;
// logo大小默认为照片的1/5
public static final int DEFAULT_LOGOPART = 5;
private final int border;
private final Color borderColor;
private final int logoPart;
/**
* Creates a default config with on color {@link #BLACK} and off color
* {@link #WHITE}, generating normal black-on-white barcodes.
*/
public MatrixToLogoImageConfig() {
this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART, DEFAULT_BORDER);
}
public MatrixToLogoImageConfig(Color borderColor, int logoPart, int border) {
this.borderColor = borderColor;
this.logoPart = logoPart;
this.border = border;
}
public Color getBorderColor() {
return borderColor;
}
public int getBorder() {
return border;
}
public int getLogoPart() {
return logoPart;
}
}
\ No newline at end of file
package com.spacetech.common.utils.QrUtil;
import java.awt.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.zxing.common.BitMatrix;
import com.spacetech.common.utils.OSSClientUtil;
import com.spacetech.common.utils.StringUtil;
public class QrUtil {
private static Logger logger = LoggerFactory.getLogger(QrUtil.class);
/**
* 生成二维码
*
* @param icon
* @param url
* @return
*/
private static final Boolean INTERNAL_OSS = false;
public static String getQRcode(String localfileDic, String icon, String url, Boolean saveLocalfile,
String localfileInternet) {
String qrcodeUrl = "";
try {
logger.info("创建调查问卷10生成二维码 releaseurl=" + icon);
String filename = StringUtil.getIdGenerator() + ".jpg";
localfileDic = OSSClientUtil.getSotreFilePath(localfileDic);
BitMatrix matrix = MatrixToImageWriterEx.createQRCode(url, 600, 600);
MatrixToLogoImageConfig logoConfig = new MatrixToLogoImageConfig(Color.WHITE, 4, 10);
logger.info("创建调查问卷11生成二维码 releaseurl=" + icon);
MatrixToImageWriterEx.writeToFile(matrix, "jpg", localfileDic + filename, icon, logoConfig);
qrcodeUrl = OSSClientUtil.putFile(localfileDic + filename, true, INTERNAL_OSS, saveLocalfile,
localfileInternet);
logger.info("创建调查问卷13生成二维码 releaseurl=" + icon);
} catch (Exception e) {
e.printStackTrace();
logger.info("创建调查问卷19生成二维码 releaseurl=", e);
}
return qrcodeUrl;
}
public static String getQRcodeWithName(String localfileDic, String icon, String url, Boolean saveLocalfile,
String localfileInternet, String fileName) {
String qrcodeUrl = "";
try {
logger.info("创建调查问卷10生成二维码 releaseurl=" + icon);
String filename = fileName + ".jpg";
localfileDic = OSSClientUtil.getSotreFilePath(localfileDic);
BitMatrix matrix = MatrixToImageWriterEx.createQRCode(url, 600, 600);
MatrixToLogoImageConfig logoConfig = new MatrixToLogoImageConfig(Color.WHITE, 4, 10);
logger.info("创建调查问卷11生成二维码 releaseurl=" + icon);
MatrixToImageWriterEx.writeToFile(matrix, "jpg", localfileDic + filename, icon, logoConfig);
qrcodeUrl = OSSClientUtil.putFile(localfileDic + filename, true, INTERNAL_OSS, saveLocalfile,
localfileInternet);
logger.info("创建调查问卷13生成二维码 releaseurl=" + icon);
} catch (Exception e) {
e.printStackTrace();
logger.info("创建调查问卷19生成二维码 releaseurl=", e);
}
return qrcodeUrl;
}
}
package com.spacetech.common.utils;
import java.net.NetworkInterface;
import java.util.Enumeration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SnowflakeUtils {
private static Logger logger = LoggerFactory.getLogger(SnowflakeUtils.class);
private long workerId; // 这个就是代表了机器id
private long datacenterId; // 这个就是代表了机房id
private long sequence; // 这个就是代表了一毫秒内生成的多个id的最新序号
public SnowflakeUtils(long workerId, int dubboid) {
// sanity check for workerId
// 这儿不就检查了一下,要求就是你传递进来的机房id和机器id不能超过32,不能小于0
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(
String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(
String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = dubboid;
this.sequence = 0;
}
private long twepoch = 1288834974657L;
private long workerIdBits = 5L;
private long datacenterIdBits = 5L;
// 这个是二进制运算,就是5 bit最多只能有31个数字,也就是说机器id最多只能是32以内
private long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 这个是一个意思,就是5 bit最多只能有31个数字,机房id最多只能是32以内
private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private long sequenceBits = 12L;
private long workerIdShift = sequenceBits;
private long datacenterIdShift = sequenceBits + workerIdBits;
private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private long sequenceMask = -1L ^ (-1L << sequenceBits);
private long lastTimestamp = -1L;
public long getWorkerId() {
return workerId;
}
public long getDatacenterId() {
return datacenterId;
}
public long getTimestamp() {
return System.currentTimeMillis();
}
// 这个是核心方法,通过调用nextId()方法,让当前这台机器上的snowflake算法程序生成一个全局唯一的id
public synchronized long nextId() {
// 这儿就是获取当前时间戳,单位是毫秒
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
System.err.printf("clock is moving backwards. Rejecting requests until %d.", lastTimestamp);
throw new RuntimeException(String.format(
"Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
// 下面是说假设在同一个毫秒内,又发送了一个请求生成一个id
// 这个时候就得把seqence序号给递增1,最多就是4096
if (lastTimestamp == timestamp) {
// 这个意思是说一个毫秒内最多只能有4096个数字,无论你传递多少进来,
// 这个位运算保证始终就是在4096这个范围内,避免你自己传递个sequence超过了4096这个范围
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
// 这儿记录一下最近一次生成id的时间戳,单位是毫秒
lastTimestamp = timestamp;
// 这儿就是最核心的二进制位运算操作,生成一个64bit的id
// 先将当前时间戳左移,放到41 bit那儿;将机房id左移放到5 bit那儿;将机器id左移放到5 bit那儿;将序号放最后12 bit
// 最后拼接起来成一个64 bit的二进制数字,转换成10进制就是个long型
long result = 2000000000000000000l + ((timestamp - twepoch) << timestampLeftShift)
| (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;
return result;
}
public static String getMacAddress() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
byte[] mac = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || netInterface.isPointToPoint()
|| !netInterface.isUp()) {
continue;
} else {
mac = netInterface.getHardwareAddress();
if (mac != null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
if (sb.length() > 0) {
return sb.toString();
}
}
}
}
} catch (Exception e) {
System.out.print("MAC地址获取失败");
}
return "";
}
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
}
package com.spacetech.common.utils;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
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.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.common.exception.ApiException;
import com.spacetech.common.exception.BusinessException;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
public class StringUtil {
private final static DecimalFormat decimalFormat = new DecimalFormat("0.00");
private final static DecimalFormat DECIMAL_FORMAT_FOUR = new DecimalFormat("0.0000");
public final static Double THOUSAND_NUM = 10000D;
public static final String MSG_NEWLINE = "\n";
public static final String MSG_SPACE = " ";
// 转义时标识
private static final char unicode_separator = '&';
private static final char unicode_prefix = 'u';
private static final char separator = ':';
public static final String RETURN_MSG_SAVE_SUCCESS = "保存成功";
public static final String RETURN_MSG_SAVE_FAIL = "保存失败";
public static final String RETURN_MSG_UPDATE_SUCCESS = "更新成功";
public static final String RETURN_MSG_FIND_NO_DATA = "没有数据";
public static final String RETURN_MSG_DELETE_FAIL = "删除失败";
public static final String RETURN_MSG_DELETE_SUCCESS = "删除成功";
public static final String RETURN_MSG_EXPORT_FAIL = "导出失败";
public static final String RETURN_MSG_SUCCESS = "success";
public static final String RETURN_MSG_FAIL = "fail";
public static final String VIEW_IF_NO_CLASS = "班级不存在";
public static final String VIEW_IF_NO_STUDENT = "学生不存在";
public static final String VIEW_IF_NO_NAME = "用户不存在";
public static final String[] CHINESE_NUMBER = new String[] { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一",
"十二", "十三", "十四", "十五" };
public static final int NUMBER_SCALE = 2;
private static Logger logger = LoggerFactory.getLogger(StringUtil.class);
static Random r = new Random();
private static double EARTH_RADIUS = 6378.137;// 地球半径
private StringUtil() {
};
public static String getURLEncoderString(String str) {
String result = "http:/";
String pureurl = str.substring(7, str.length());
String[] urls = pureurl.split("/");
for (String url : urls) {
try {
result += "/" + java.net.URLEncoder.encode(url, "GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return result;
}
// public static String encodeBASE64(String s) {
// if (s == null)
// return null;
// try {
// return new String(Base64.encodeBase64(s.getBytes()), "UTF-8");
// } catch (UnsupportedEncodingException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// return null;
// }
// // return Base64.encodeBase64String(s.getBytes());
// // return (new BASE64Encoder()).encode(s.getBytes());
// }
public static long getRandom18Long() {
return System.currentTimeMillis() * 100000 + r.nextInt(90000) + 10000;
}
/**
* 将BASE64字符串进行解密
*
* @return
*/
// public static String decodeBASE64(String s) {
// if (s == null)
// return null;
//
// try {
// byte[] b = Base64.decodeBase64(s.getBytes("UTF-8"));
// ;
// return new String(b);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
public static <E> List<E> toList(Iterable<E> iterable) {
if (iterable instanceof List) {
return (List<E>) iterable;
}
ArrayList<E> list = new ArrayList<E>();
if (iterable != null) {
for (E e : iterable) {
list.add(e);
}
}
return list;
}
/**
* 判断字符串是否为空
*/
public static boolean isNullOrEmpty(String str) {
if (str == null || str.length() <= 0 || str.trim() == null || str.trim().length() <= 0) {
return true;
}
return false;
}
/**
* 判断字符串是否不为空
*/
public static boolean isNotEmpty(String str) {
return !isNullOrEmpty(str);
}
/**
* 字符串首字母转大写
*
* @param string
* @return
*/
public static String firstLetterToStringUpperCase(String string) {
return string.substring(0, 1).toUpperCase() + string.substring(1);
}
/**
*
* @param str
* @return
*/
public static int getIntOfStr(String str) {
try {
return new Integer(str).intValue();
} catch (Exception e) {
return 0;
}
}
/**
* 处理 1,2格式的字符串,处理为 '1','2'
*
* @return
*/
public static String processSplitStr(String splitStr) {
StringBuffer sb = new StringBuffer();
String[] splitStrs = splitStr.split(",");
sb.append("'").append(splitStrs[0]).append("'");
for (int i = 1; i < splitStrs.length; i++) {
sb.append(",'").append(splitStrs[i]).append("'");
}
return sb.toString();
}
public static int getIntOfObj(Object obj) {
try {
return new Integer(obj.toString()).intValue();
} catch (Exception e) {
return 0;
}
}
public static boolean getBooleanOfObj(Object object) {
try {
return (Boolean) object;
} catch (Exception e) {
return false;
}
}
public static boolean getBooleanOfInt(int i) {
return i == 0 ? false : true;
}
public static long getLongOfObj(Object obj) {
try {
return new Long(obj.toString()).longValue();
} catch (Exception e) {
return 0;
}
}
/**
* 如果转换失败,返回-2
*
* @param obj
* @return
*/
public static double getDoubleOfObj(Object obj) {
try {
return new Double(obj.toString()).doubleValue();
} catch (Exception e) {
return 0;
}
}
public static Double getThousandMoney(Object obj, Integer scale) {
try {
double value = getDoubleOfObj(obj);
if (value == 0D) {
return 0D;
}
return StringUtil.div(value, THOUSAND_NUM, scale);
} catch (Exception e) {
return 0D;
}
}
/**
* 如果转换失败,返回-2
*
* @param obj
* @return
*/
public static float getFloatOfObj(Object obj) {
try {
return new Float(obj.toString()).floatValue();
} catch (Exception e) {
return -2;
}
}
/**
* 如果转换失败,返回-2
*
* @param obj
* @return
*/
public static float getNullFloat(Object obj) {
try {
return new Float(obj.toString()).floatValue();
} catch (Exception e) {
return 0;
}
}
/**
* 将浮点型保留两位小数
*/
public static String formartDecimal(Object d) {
try {
String str = new java.text.DecimalFormat("#.00").format(d);
if (str.charAt(0) == '.') // 0.01 格式化为 .01
{
str = "0" + str;
}
if (str.indexOf("-.") == 0) // -.01 开头
{
str = "-0." + str.substring(2);
}
if (str.equals("0") || str.equals("0.00")) {
str = "0";
}
return str.replace("-0.00", "").replace(".00", "");
} catch (Exception e) {
return "";
}
}
public static int[] getIntOfObjArry(Object[] objs) {
int[] result = new int[objs.length];
for (int i = 0; i < objs.length; i++) {
result[i] = getIntOfObj(objs[i]);
}
return result;
}
/**
* 返回对象字符串,对于出错情况返回空字符串
*
* @param obj
* @return
*/
public static String toString(Object obj) {
try {
return obj == null ? "" : obj.toString();
} catch (Exception e) {
return "";
}
}
public static String getNullStr(Object obj) {
try {
return obj.toString();
} catch (Exception e) {
return "";
}
}
/**
* 截取pre和after中间的字符串
* @param str
* @param pre
* @param after
* @return
*/
public static List<String> getCentreStr(String str, String pre, String after) {
List<String> result = new ArrayList<>();
if(StringUtil.isNullOrEmpty(str) || StringUtil.isNullOrEmpty(pre) || StringUtil.isNullOrEmpty(after)){
return result;
}
String regex = pre + "(.*?)" + after;
Pattern p=Pattern.compile(regex);
Matcher m=p.matcher(str);
while(m.find()){
result.add(m.group(1));
}
return result;
}
public static void main(String[] args) {
System.out.println(StringUtil.transTimeToInt("23:05"));
System.out.println(StringUtil.transIntToTime(1385));
String s = "1!2/;;@";
String a = fomartSpecialString(s);
System.out.println("a=" + a);
System.out.println("a=" + getIdGenerator());
String content = "ddd";
String abc = clearInvisibleCharacter(content);
System.out.println("abc=" + abc);
String source = "啊啊啊等333AASS33/n啊啊啊";
String emojiStr = filterEmoji(source);
System.out.println("emojiStr=" + emojiStr);
long random = (long) (Math.random() * 9000000000l) + 90000000000l;// 生成8位随机数
System.out.println(random);
String aa = "<span style='color:red'>[09:00到校]迟到</span><br><a @click=\"gridmethods.showDetail(1,2217126,'2019-11-28 09:55:08.0')\">09:55:08离校</a>";
List<String> aaa = removeTagFromText1(aa);
System.out.println(aaa);
String aaa1 = "";
System.out.println(getNullWxAppid(""));
}
public static String filterEmoji(String source) {
if (StringUtil.isNotEmpty(source)) {
Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
Matcher emojiMatcher = emoji.matcher(source);
if (emojiMatcher.find()) {
source = emojiMatcher.replaceAll("");
return source;
}
return source;
}
return source;
}
public static String getTrimStr(String obj) {
try {
return obj.trim();
} catch (Exception e) {
return "";
}
}
/**
* 将以逗号隔开的字符串转换为集合
*
* @param str
* @return
*/
public static List<Integer> getNullStrToList(String str) {
String num[] = str.split(",");
List<Integer> stateList = new ArrayList<Integer>();
if (StringUtil.isNotEmpty(str) && num.length > 0 && !str.equals("null")) {
for (int i = 0; i < num.length; i++) {
String value = StringUtil.getNullStr(num[i]).trim();
stateList.add(Integer.parseInt(value));
}
} else {
stateList.add(0);
}
return stateList;
}
/**
* 除去字符串里的] [ "
*
* @param str
* ,
* @return
*/
public static String getNullStrToNoAsteriskAndBrackets(String str) {
if (StringUtil.isNotEmpty(str) && !str.equals("null")) {
str = str.replace("[", "");
str = str.replace("\"", "");
str = str.replace("]", "");
} else {
str = "";
}
return str;
}
/**
* 将以逗号隔开的字符串转换为集合
*
* @param str
* @return
*/
public static List<String> getNullStrToStringList(String str) {
String num[] = str.split(",");
List<String> stateList = new ArrayList<String>();
if (StringUtil.isNotEmpty(str) && num.length > 0 && !str.equals("null")) {
for (int i = 0; i < num.length; i++) {
stateList.add(num[i]);
}
} else {
stateList.add("");
}
return stateList;
}
/**
* 将以指定的字符隔开的字符串转换为集合
*
* @param str
* @param operator
* @return
*/
public static List<String> getNullStrToStringListByOperator(String str, String operator) {
String num[] = str.split(operator);
List<String> stateList = new ArrayList<String>();
if (StringUtil.isNotEmpty(str) && num.length > 0 && !str.equals("null")) {
for (int i = 0; i < num.length; i++) {
stateList.add(num[i]);
}
} else {
stateList.add("");
}
return stateList;
}
/**
* 将以逗号隔开的字符串转换为集合
*
* @param str
* @return
*/
public static List<Long> getNullStrToLongList(String str) {
List<Long> stateList = new ArrayList<Long>();
if (StringUtil.isNotEmpty(str)) {
String num[] = str.split(",");
if (num.length > 0) {
for (int i = 0; i < num.length; i++) {
stateList.add(StringUtil.getNullLong(num[i]));
}
}
} else {
stateList.add(0L);
}
return stateList;
}
/**
* SQL查询时 like setParameter 加上%%
*
* @param obj
* @return
*/
public static String getNullStrLike(Object obj) {
try {
return "%" + obj.toString() + "%";
} catch (Exception e) {
return "%" + "" + "%";
}
}
/**
* SQL查询时 like setParameter 右侧加上%
*
* @param obj
* @return
*/
public static String getNullStrLikeSineRight(Object obj) {
try {
return obj.toString() + "%";
} catch (Exception e) {
return "" + "%";
}
}
/**
* 得到Long数据
*
* @param obj
* @return
*/
public static Long getNullLong(Object obj) {
try {
return Long.valueOf(obj.toString());
} catch (Exception e) {
return 0L;
}
}
/**
* 自动将字符串补足10位 ,如1111——》0000001111
*
* @param kh
* @return
*/
public static String fixToTen(String kh) {
if (StringUtil.isNotEmpty(kh) && kh.length() < 10) {
for (int i = 10 - kh.length(); i > 0; i--) {
kh = "0" + kh;
}
}
return kh;
}
// public static String getIdGenerator() throws BusinessException {
// String idEntity = "";
// try {
// idEntity = DateUtil.getFormatDate(new Date());
// int random = (int) (Math.random() * 90000000) + 10000000;// 生成8位随机数
// String randoms = String.valueOf(random);
// idEntity = idEntity + randoms;
// // log.info("id=" + idEntity);
// } catch (Exception e) {
// e.printStackTrace();
// throw new BusinessException("主键生成失败");
// }
// return idEntity;
// }
// public static Long getBigIntId() {
// return getNullLong(getIdGenerator());
// }
/**
* System.currentTimeMillis+10位随机字符
*
* @return
*/
public static String randomstr() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 10; i++) {
int intVal = (int) (Math.random() * 26 + 97);
sb.append((char) intVal);
}
return "YEY_" + System.currentTimeMillis() + sb.toString();
}
public static String getWeekStr(int day) {
String weekStr = null;
switch (day) {
case 1:
weekStr = "星期一";
break;
case 2:
weekStr = "星期二";
break;
case 3:
weekStr = "星期三";
break;
case 4:
weekStr = "星期四";
break;
case 5:
weekStr = "星期五";
break;
case 6:
weekStr = "星期六";
break;
case 7:
weekStr = "星期日";
break;
}
return weekStr;
}
/**
* 产生6位随机数,不足补零
*
* @return
*/
public static String get6RandomStr() {
int result = 0;
Random rand = new Random();
result = rand.nextInt(999999);
return "000000".substring((result + "").length()) + result;
}
public static String removeTagFromText(String content) {
if (StringUtil.isNullOrEmpty(content)) {
return "";
}
Pattern p = null;
Matcher m = null;
String value = null;
// 去掉<>标签
p = Pattern.compile("(<[^>]*>)");
m = p.matcher(content);
String temp = content;
while (m.find()) {
value = m.group(0);
temp = temp.replace(value, "");
}
// 去掉换行或回车符号
p = Pattern.compile("(/r+|/n+)");
m = p.matcher(temp);
while (m.find()) {
value = m.group(0);
temp = temp.replace(value, " ");
}
if (StringUtil.isNotEmpty(temp)) {
temp = temp.replaceAll("&nbsp;", "");
}
if (StringUtil.isNotEmpty(temp)) {
temp = temp.replaceAll("\n", "");
temp = temp.replaceAll("\t", "");
}
if (StringUtil.isNotEmpty(temp)) {
temp = temp.replaceAll(" ", "");
}
return temp;
}
public static String removeTagFromTextKeepSpace(String content) {
if (StringUtil.isNullOrEmpty(content)) {
return "";
}
Pattern p = null;
Matcher m = null;
String value = null;
// 去掉<>标签
p = Pattern.compile("(<[^>]*>)");
m = p.matcher(content);
String temp = content;
while (m.find()) {
value = m.group(0);
temp = temp.replace(value, "");
}
// 去掉换行或回车符号
p = Pattern.compile("(/r+|/n+)");
m = p.matcher(temp);
while (m.find()) {
value = m.group(0);
temp = temp.replace(value, " ");
}
if (StringUtil.isNotEmpty(temp)) {
temp = temp.replaceAll("&nbsp;", "");
}
if (StringUtil.isNotEmpty(temp)) {
temp = temp.replaceAll("\n", "");
temp = temp.replaceAll("\t", "");
}
return temp;
}
// 去除标签返回List
public static List<String> removeTagFromText1(String content) {
if (StringUtil.isNullOrEmpty(content)) {
return new ArrayList<>();
}
Pattern p = null;
Matcher m = null;
String value = null;
// 去掉<>标签
p = Pattern.compile("(<[^>]*>)");
m = p.matcher(content);
String temp = content;
while (m.find()) {
value = m.group(0);
temp = temp.replace(value, "-");
}
// 去掉换行或回车符号
p = Pattern.compile("(/r+|/n+)");
m = p.matcher(temp);
while (m.find()) {
value = m.group(0);
temp = temp.replace(value, " ");
}
if (StringUtil.isNotEmpty(temp)) {
temp = temp.replaceAll("&nbsp;", "");
}
if (StringUtil.isNotEmpty(temp)) {
temp = temp.replaceAll("\n", "");
temp = temp.replaceAll("\t", "");
}
if (StringUtil.isNotEmpty(temp)) {
temp = temp.replaceAll(" ", "");
}
List<String> temps = getNullStrToStringListByOperator(temp, "-").stream()
.filter(te -> StringUtil.isNotEmpty(te)).collect(Collectors.toList());
return temps;
}
/**
* 去掉<>标签
*
* @param content
* @return
*/
public static String removeHtmlTagFromText(String content) {
try {
Pattern p = null;
Matcher m = null;
String value = null;
// 去掉<>标签
p = Pattern.compile("(<[^>]*>)");
m = p.matcher(content);
String temp = content;
while (m.find()) {
value = m.group(0);
temp = temp.replace(value, "");
}
return temp;
} catch (Exception e) {
e.printStackTrace();
return content;
}
}
public static String getImg(String content) {
if (StringUtil.isNullOrEmpty(content)) {
return "";
}
Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");// <img[^<>]*src=[\'\"]([0-9A-Za-z.\\/]*)[\'\"].(.*?)>");
Matcher m = p.matcher(content);
while (m.find()) {
String img = StringUtil.getNullStr(m.group(1));
if (StringUtil.isNotEmpty(img) && !(img.indexOf("static/kindeditor/plugins/emoticons/images") > -1)
&& !(img.indexOf("135editor.com/cache") > -1) && !(img.indexOf("wxteditor") > -1)
&& !(img.indexOf("/135ueditor") > -1) && !(img.indexOf("/fileTypeImages") > -1)) {// 表情包路径,不显示图片
return img;
}
// return img;
}
return "";
}
/**
* 获取内容里的所有图片
*
* @param content
* @return
*/
public static List<String> listImg(String content, Integer num) {
if (StringUtil.isNullOrEmpty(content)) {
return new ArrayList<String>();
}
Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");// <img[^<>]*src=[\'\"]([0-9A-Za-z.\\/]*)[\'\"].(.*?)>");
Matcher m = p.matcher(content);
List<String> result = new ArrayList<>();
while (m.find()) {
String img = StringUtil.getNullStr(m.group(1));
if (StringUtil.isNotEmpty(img) && !(img.indexOf("static/kindeditor/plugins/emoticons/images") > -1)
&& !(img.indexOf("135editor.com/cache") > -1) && !(img.indexOf("wxteditor") > -1)
&& !(img.indexOf("/135ueditor") > -1) && !(img.indexOf("/fileTypeImages") > -1)) {// 表情包路径,不显示图片
result.add(img);
num--;
}
if (num == 0) {
return result;
}
// return img;
}
return result;
}
//
// public static String getImg(String content) {
// if (StringUtil.isNullOrEmpty(content)) {
// return "";
// }
// Pattern p = Pattern
// .compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");//
// <img[^<>]*src=[\'\"]([0-9A-Za-z.\\/]*)[\'\"].(.*?)>");
// Matcher m = p.matcher(content);
// if (m.find()) {
// String img = StringUtil.getNullStr(m.group(1));
// if (img.indexOf("static/kindeditor/plugins/emoticons/images") > -1) {//
// 表情包路径,不显示图片
// return "";
// }
// // System.out.println("m.group():"+m.group());
// // System.out.println("m.group(1):"+m.group(1));
// return img;
// } else
// return "";
// }
public static String URLDecoder(String s) throws Exception {
try {
return new String(s.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
throw new Exception("URL编码失败");
}
}
/**
* 格式化字符,去除特殊字符
*
* @param s
* @return
*/
public static String removeSpecialString(String s) {
String result = "";
try {
if (StringUtil.isNotEmpty(s)) {
result = s.replace("-", "031d0e7f454111e790907cd30abc9b82");
result = s.replaceAll(
"[^(`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?a-zA-Z0-9\\u4e00-\\u9fa5)]",
"");
if (StringUtil.isNotEmpty(result)) {
result = s.replaceAll("031d0e7f454111e790907cd30abc9b82", "-");
}
}
return result;
} catch (Exception e) {
e.printStackTrace();
return s;
}
}
/**
* 格式化字符,只剩下文字、数字
*
* @param s
* @return
*/
public static String FormatString(String s) {
String result = "";
try {
if (StringUtil.isNotEmpty(s)) {
result = s.replaceAll("[^(a-zA-Z0-9)]", "");
}
return result;
} catch (Exception e) {
e.printStackTrace();
return s;
}
}
/**
* 给字符串中的img标签前后添加A标签 A.href = img.src 如果alt为空,则方法不生效 该方法只能适用于img格式为如下形式
* <img src="jpg" alt="" />
*
* @param str
* @param alt
* @return
*/
public static String addAofImg(String str, String alt) {
String result = str;
try {
if (str.isEmpty() || alt.isEmpty()) {
return str;
}
int index = 0;
/* 方法通过改变alt的值获取下一个img标签 */
while (str.indexOf("alt=\"\"") != -1) {
// 获取字符串中图片路径
String src = str.substring(str.indexOf("src=\"", str.indexOf("<img", index)) + 5,
str.indexOf("\"", str.indexOf("src=\"", str.indexOf("<img", index)) + 5));
if (str.indexOf("alt=\"\" />") != -1) {
// 给字符串中img标签前面添加<a>标签
str = str.substring(0, str.indexOf("<img", index)) + "<a href=\"" + src + "\"><img"
+ str.substring(str.indexOf("<img", index) + 4);
index = str.indexOf("alt=\"\" />");
// 添加alt的值,通知在img后面添加</a>标签
str = str.substring(0, str.indexOf("alt=\"\" />")) + "alt=\"" + alt + "\" />" + "</a>"
+ str.substring(str.indexOf("alt=\"\" />") + 9);// 截取后再加
} else {
// 给字符串中img标签前面添加<a>标签
str = str.substring(0, str.indexOf("<img", index)) + "<a href=\"" + src + "\"><img alt=\"" + alt
+ "\"" + str.substring(str.indexOf("<img alt=\"\"", index) + 11);
index = str.indexOf("\"", str.indexOf("src=\"", str.indexOf("<img", index)) + 5);
// 添加alt的值,通知在img后面添加</a>标签
str = str.substring(0, index + 4) + "</a>" + str.substring(index + 4);// 截取后再加
}
}
} catch (Exception e) {
e.printStackTrace();
return result;
}
return str;
}
/**
* 截取字符串前面的正整数,如"22天"得"22","18个人"得到"18".
*
* @return
*/
public static String getQuantity(String regular) {
int index = 0;
for (int i = 0; i < regular.length(); i++) {
char c = regular.charAt(i);
if (Character.isDigit(c)) {
if (i == regular.length() - 1) {
index = i + 1;
} else {
index = i;
}
continue;
} else {
index = i;
break;
}
}
return regular.substring(0, index);
}
// public static String getPinYin(String src) {
// char[] t1 = null;
// t1 = src.toCharArray();
// String[] t2 = new String[t1.length];
// // 设置汉字拼音输出的格式
// HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
// t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
// t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
// t3.setVCharType(HanyuPinyinVCharType.WITH_V);
// String t4 = "";
// int t0 = t1.length;
// try {
// for (int i = 0; i < t0; i++) {
// // 判断能否为汉字字符
// // System.out.println(t1[i]);
// if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
// t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
// if (t2 != null) {
// t4 += t2[0];
// }
// } else {
// // 如果不是汉字字符,间接取出字符并连接到字符串t4后
// t4 += Character.toString(t1[i]);
// }
// }
// } catch (BadHanyuPinyinOutputFormatCombination e) {
// e.printStackTrace();
// }
// return t4;
// }
public static String getSubstringStr(String src, int beginIndex, int endIndex) {
try {
return src.substring(beginIndex, endIndex);
} catch (Exception e) {
return "";
}
}
public static String getSubstringStr(String src, int beginIndex) {
try {
return src.substring(beginIndex);
} catch (Exception e) {
return "";
}
}
public static String getRateData(String numerator, String denominator) {
String rate = "0%";
if (StringUtil.isNotEmpty(denominator) && !StringUtil.getNullStr(denominator).equals("0")
&& !StringUtil.getNullStr(numerator).equals("0")) {
return StringUtil.formartDecimal(
StringUtil.getDoubleOfObj(numerator) / StringUtil.getDoubleOfObj(denominator) * 100) + "%";
}
return rate;
}
/**
* 判断字符串数组中是否包含某字符串元素
*
* @param substring
* 某字符串
* @param source
* 源字符串数组
* @return 包含则返回true,否则返回false
*/
public static boolean isIn(String substring, String[] source) {
if (source == null || source.length == 0) {
return false;
}
for (int i = 0; i < source.length; i++) {
String aSource = source[i];
if (aSource.equals(substring)) {
return true;
}
}
return false;
}
// public static List<Integer> getAllState() {
// List<Integer> stateList = new ArrayList<Integer>();
// stateList.add(ConstantVar.STATE_OPEN);
// stateList.add(ConstantVar.STATE_STOP);
// return stateList;
// }
/**
* 判断Long类型是否空或者零
*/
public static boolean isNullOrEmpty(Long strLong) {
if (strLong == null || strLong == 0L || strLong.equals(0L)) {
return true;
}
return false;
}
public static String guid() {
Random rd = new Random();
char[] strRandomList = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
String result = "";
for (int i = 0; i < 32; i++) {
result += strRandomList[rd.nextInt(strRandomList.length)];// 随机取strRandomList的项值
}
return result;
}
/**
* 判断Long类型是否空或者零
*/
public static boolean isNotEmpty(Long strLong) {
return !isNullOrEmpty(strLong);
}
public static Integer getRandom4Int() {
return r.nextInt(9000) + 1000;
}
public static Integer getRandom6Int() {
return r.nextInt(900000) + 100000;
}
public static Integer getRandom9Long() {
return r.nextInt(900000000) + 100000;
}
public static Long getRandom11Long() {
return (long) (Math.random() * 9000000000l) + 90000000000l;// 生成11位随机数
}
public static String getRandomSerialnumber() {
String serialnumber = UUID.randomUUID().toString();
serialnumber = serialnumber.replaceAll("-", "");
return serialnumber;
}
/**
* 空字符或null时,返回0
*/
public static String getZeroByNullOrEmpty(Object obj) {
String str = StringUtil.getNullStr(obj);
if (isNullOrEmpty(str)) {
return "0";
}
return str;
}
public static String getRandomCharAndNumr(Integer length) {
String str = "";
Random random = new Random();
for (int i = 0; i < length; i++) {
boolean b = random.nextBoolean();
if (b) { // 字符串
int choice = random.nextBoolean() ? 65 : 97; // 取得65大写字母还是97小写字母
str += (char) (choice + random.nextInt(26));// 取得大写字母
} else { // 数字
str += String.valueOf(random.nextInt(10));
}
}
// 如果是纯字母或纯数字 则重新生成
if (isRandomUsable(str)) {
str = getRandomCharAndNumr(length);
}
return str;
}
/**
* 验证随机字母数字组合是否纯数字与纯字母
*/
public static boolean isRandomUsable(String str) {
// String regExp =
// "^[A-Za-z]+(([0-9]+[A-Za-z0-9]+)|([A-Za-z0-9]+[0-9]+))|[0-9]+(([A-Za-z]+[A-Za-z0-9]+)|([A-Za-z0-9]+[A-Za-z]+))$";
String regExp = "^([0-9]+)|([A-Za-z]+)$";
Pattern pat = Pattern.compile(regExp);
Matcher mat = pat.matcher(str);
return mat.matches();
}
/**
* 验证随机字母数字组合是否只有字母与数字
*
* @param string
* @return
*/
public static boolean isConSpeCharacters(String string) {
if (string.replaceAll("[a-z]*[A-Z]*\\d*", "").length() == 0) {
// 如果不包含特殊字符
return false;
}
return true;
}
public static boolean checkNumValue(String str) {
String reg = "^[\\-\\+]?\\d+(\\.\\d+)?";
Pattern pat = Pattern.compile(reg);
Matcher mat = pat.matcher(str);
return mat.matches();
}
/**
* 去除字符串中的空格、回车、换行符、制表符
*
* @param str
* @return
*/
public static String replaceBlank(String str) {
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
/**
* 判断字符串是否包含一些字符
*/
public static boolean containsString(String src, String dest) {
src = "," + getNullStr(src) + ",";
dest = "," + getNullStr(dest) + ",";
boolean flag = false;
if (src.contains(dest)) {
flag = true;
}
return flag;
}
public static List<Long> getNullIdList(List<Object[]> objList, int num) {
List<Long> idList = new ArrayList<Long>();
idList.add(0L);
if (objList != null && objList.size() > 0) {
for (Object[] obj : objList) {
idList.add(getNullLong(obj[num]));
}
}
return idList;
}
public static List<String> getNullStrIdList(List<Object[]> objList, int num) {
List<String> idList = new ArrayList<String>();
idList.add("0");
if (objList != null && objList.size() > 0) {
for (Object[] obj : objList) {
idList.add(getNullStr(obj[num]));
}
}
return idList;
}
/**
* JSON字符串特殊字符处理,比如:“\A1;1300”
*
* @param s
* @return String
*/
public static String string2Json(String s) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '\"':
sb.append("");
break;
// case '\\':
// sb.append("");
// break;
// case '/':
// sb.append("");
// break;
case '\b':
sb.append("");
break;
case '\f':
sb.append("");
break;
case '\n':
sb.append("");
break;
case '\r':
sb.append("");
break;
case '\t':
sb.append("");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
public static String makeLongListToStr(List<Long> list) {
if (list != null && !list.isEmpty()) {
String str = list.toString();
return str.substring(1, str.length() - 1).replace(" ", "");
} else {
return "";
}
}
public static String makeStringListToStr(List<String> list) {
if (list != null && !list.isEmpty()) {
String str = list.toString();
return str.substring(1, str.length() - 1).replace(" ", "");
} else {
return "";
}
}
/**
* 去除字符串结尾的逗号
*/
public static String removeEndswithComma(String str) {
if (isNotEmpty(str)) {
if (str.endsWith(",")) {
str = str.substring(0, str.length() - 1);
}
}
return str;
}
public static String joinArrToStrWithComma(String[] strArr) {
StringBuilder sb = new StringBuilder();
if (strArr != null) {
for (String s : strArr) {
sb.append(s + ",");
}
}
return removeEndswithComma(sb.toString());
}
/**
* 比较 2个字符串(以','连接的多个字符串元素)是否每个元素都相互包含。。。。
*
* @param str1
* @param str2
* @return
*/
public static boolean compareWhichJoinWithComma(String str1, String str2) {
List<String> list1 = StringUtil.getNullStrToStringList(StringUtil.getNullStr(str1));
List<String> list2 = StringUtil.getNullStrToStringList(StringUtil.getNullStr(str2));
if (list1.size() != list2.size())
return false;
if (!list1.containsAll(list2))
return false;
if (!list2.containsAll(list1))
return false;
return true;
}
/**
* 字符串(以','连接的多个字符串元素)去除重复的子元素
*
* @return
*/
public static String removeRepeatElements(String str) {
List<String> list = StringUtil.getNullStrToStringList(StringUtil.getNullStr(str));
List<String> result = new ArrayList<String>();
for (String s : list) {
if (!result.contains(s)) {
result.add(s);
}
}
return makeStringListToStr(result);
}
// 替换所有的回车换行
public static String transferString(String content) {
String string_temp = content;
try {
if (StringUtil.isNotEmpty(content)) {
string_temp = string_temp.replaceAll("<BR>", "\n");
}
} catch (Exception e) {
// alert(e.message);
return string_temp;
}
return string_temp;
}
/**
* 转码 /** 生成随机length 位数字和字母.
*
* @param length
* @return
*/
public static String getStringRandom(int length) {
String val = "";
Random random = new Random();
// 参数length,表示生成几位随机数
for (int i = 0; i < length; i++) {
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
// 输出字母还是数字
if ("char".equalsIgnoreCase(charOrNum)) {
// 输出是大写字母还是小写字母
int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
val += (char) (random.nextInt(26) + temp);
} else if ("num".equalsIgnoreCase(charOrNum)) {
val += String.valueOf(random.nextInt(10));
}
}
if (isNumeric(val)) {
val = getStringRandom(length);
}
return val;
}
public static String unicodeToString(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
Matcher matcher = pattern.matcher(str);
char ch;
while (matcher.find()) {
ch = (char) Integer.parseInt(matcher.group(2), 16);
str = str.replace(matcher.group(1), ch + "");
}
return str;
}
/**
* 将浮点型保留一位小数
*/
public static float formartOneDecimal(Object d) {
if (d == null) {
return StringUtil.getFloatOfObj(0);
}
String str = new java.text.DecimalFormat("#.0").format(d);
if (str.charAt(0) == '.') // 0.1 格式化为 .01
{
str = "0" + str;
}
if (str.indexOf("-.") == 0) // -.01 开头
{
str = "-0." + str.substring(1);
}
if (str.equals("0") || str.equals("0.0")) {
str = "0";
}
return StringUtil.getFloatOfObj(str.replace("-0.0", "").replace(".0", ""));
}
/**
* 判断字符传是全为数字.
*
* @param str
* @return
*/
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
/**
* 得到integer数据
*
* @param obj
* @return
*/
public static Integer getIntegerOfObj(Object obj) {
try {
return Integer.valueOf(obj.toString());
} catch (Exception e) {
return Integer.valueOf(0);
}
}
/**
* 将Object转为int,如果Object为null返回0
*
* @param obj
* @return
*/
public static int getNullInt(Object obj) {
try {
return Integer.parseInt(obj.toString());
} catch (Exception e) {
return 0;
}
}
public static int transToIDisplayStart(int pageIndex, int pageSize) {
return (pageIndex - 1) * pageSize;
}
/**
* 入参格式:05:05
*
* @param time
* @return
*/
public static int transTimeToInt(String time) {
try {
String[] str = time.split(":");
return Integer.valueOf(str[0]) * 60 + Integer.valueOf(str[1]);
} catch (Exception e) {
throw new RuntimeException("时间格式错误");
}
}
public static String transIntToTime(Integer time) {
if (time == null) {
return "";
}
try {
String minute = (int) time / 60 + "";
String second = time % 60 + "";
if (minute.length() == 1) {
minute = "0" + minute;
}
if (second.length() == 1) {
second = "0" + second;
}
return minute + ":" + second;
} catch (Exception e) {
throw new RuntimeException("时间格式错误");
}
}
/**
* 替换html符号,存数据库前
*
* @param str
* @return
*/
public static String encodeHtml(String str) {
if (str != null) {
str = str.replace("'", "''");
str = str.replace("\"", "&quot;");
str = str.replace("<", "&lt;");
str = str.replace(">", "&gt;");
str = str.replace("\n", "<br>");
str = str.replace("“", "&ldquo;");
str = str.replace("”", "&rdquo;");
str = str.replace("\\", "&bdiag;");
}
return str;
}
/**
* 还原html符号,从数据库取出后
*
* @param str
* @return
*/
public static String decodeHtml(String str) {
if (str != null) {
str = str.replace("&rdquo;", "”");
str = str.replace("&ldquo;", "“");
str = str.replace("&gt;", ">");
str = str.replace("&lt;", "<");
str = str.replace("&quot;", "\"");
str = str.replace("''", "'");
str = str.replace("&bdiag;", "\\");
str = str.replace("&#39;", "'");
str = str.replace("<br>", "\n");
}
return str;
}
public static List<Long> extractIds(List<Object[]> dataList) {
List<Long> ids = new ArrayList<Long>();
for (Object[] obj : dataList) {
Long id = StringUtil.getNullLong(obj[0]);
ids.add(id);
}
return ids;
}
public static List<String> extractIdsToStrList(List<Object[]> dataList) {
List<String> ids = new ArrayList<String>();
for (Object[] obj : dataList) {
String id = StringUtil.getNullStr(obj[0]);
ids.add(id);
}
return ids;
}
/**
* 提供精确的加法运算。
*
* @param v1
* 被加数
* @param v2
* 加数
* @return 两个参数的和
*/
public static double add(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确的减法运算。
*
* @param v1
* 被减数
* @param v2
* 减数
* @return 两个参数的差
*/
public static double sub(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的乘法运算。
*
* @param v1
* 被乘数
* @param v2
* 乘数
* @return 两个参数的积
*/
public static double mul(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。
*
* @param v1
* 被除数
* @param v2
* 除数
* @return 两个参数的商
*/
public static double div(double v1, double v2) {
return div(v1, v2, 10);
}
public static double divPercent(double v1, double v2, int scale) {
return mul(div(v1, v2, scale + 2), 100);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。
*
* @param v1
* 被除数
* @param v2
* 除数
* @param scale
* 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1, double v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的小数位四舍五入处理。
*
* @param v
* 需要四舍五入的数字
* @param scale
* 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static Long getBigId() throws BusinessException {
String idEntity = "";
try {
idEntity = DateUtil.fomartCurrentTime(DateUtil.DATE_ALL_S);
int random = (int) (Math.random() * 90000) + 10000;// 生成8位随机数
String randoms = String.valueOf(random);
idEntity = idEntity + randoms;
// log.info("id=" + idEntity);
} catch (Exception e) {
// e.printStackTrace();
throw new BusinessException("主键生成失败");
}
return StringUtil.getNullLong(idEntity);
}
public static Long getSnowflakeId(SnowflakeUtils worker) throws Exception {
return worker.nextId();
}
public static String getIdGenerator() throws BusinessException {
String idEntity = "";
try {
idEntity = DateUtil.getFormatDate(new Date());
int random = (int) (Math.random() * 90000000) + 10000000;// 生成8位随机数
String randoms = String.valueOf(random);
idEntity = idEntity + randoms;
// log.info("id=" + idEntity);
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException("主键生成失败");
}
return idEntity;
}
public static Long getBigIntId() {
return getNullLong(getIdGenerator());
}
/**
* true:合法 <br>
* false:不合法
*
* @param phonenum
* @return
*/
public static boolean checkPhone(String phonenum) {
return StringUtil.isNullOrEmpty(phonenum) || phonenum.matches("^[0-9-]{7,13}$");
}
/**
* 校验时间格式
*
* @param date
* @return
*/
public static boolean checkDate(String date) {
boolean dateType = false;
try {
String rexp = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";
Pattern pat = Pattern.compile(rexp);
Matcher mat = pat.matcher(date);
dateType = mat.matches();
} catch (Exception e) {
return false;
}
return dateType;
}
/**
* 判断数字串是否为空 或者零
*/
public static boolean isNullOrEmpty(Integer num) {
if (num == null || num == 0) {
return true;
}
return false;
}
/**
* 判断数字串是否为空 或者零
*/
public static boolean isNotEmpty(Integer num) {
return !isNullOrEmpty(num);
}
public static boolean getBooleanByOperationStr(String str) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
boolean result = false;
try {
result = StringUtil.getBooleanOfObj(engine.eval(str));
} catch (ScriptException e) {
e.printStackTrace();
}
return result;
}
/**
* 得到中文全拼
*
* @param src
* 需要转化的中文字符串
* @return
*/
public static String getPinYin(String src) {
String t4 = "";
try {
char[] t1 = null;
t1 = src.toCharArray();
String[] t2 = new String[t1.length];
// 设置汉字拼音输出的格式
HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
t3.setVCharType(HanyuPinyinVCharType.WITH_V);
int t0 = t1.length;
for (int i = 0; i < t0; i++) {
// 判断能否为汉字字符
// System.out.println(t1[i]);
if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
if (t2 != null) {
t4 += t2[0];
}
} else {
// 如果不是汉字字符,间接取出字符并连接到字符串t4后
t4 += Character.toString(t1[i]);
}
}
} catch (Exception e) {
logger.error("getPinYin src=" + src, e);
return src;
}
return t4;
}
public static String createTimeString() {
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df.format(date);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void setColumnValue(Object obj, String columnName, String columnType, String value) {
StringBuilder methodName = new StringBuilder();
methodName.append("set").append(columnName.substring(0, 1).toUpperCase())
.append(columnName.substring(1, columnName.length()));
Method m3;
try {
Class clazz = obj.getClass();
if (columnType.equals("String")) {
m3 = clazz.getDeclaredMethod(methodName.toString(), String.class);
m3.setAccessible(false);
m3.invoke(obj, value);
} else if (columnType.equals("Integer")) {
m3 = clazz.getDeclaredMethod(methodName.toString(), Integer.class);
m3.setAccessible(false);
m3.invoke(obj, StringUtil.getIntegerOfObj(value));
} else if (columnType.equals("int")) {
m3 = clazz.getDeclaredMethod(methodName.toString(), int.class);
m3.setAccessible(false);
m3.invoke(obj, StringUtil.getIntOfObj(value));
} else if (columnType.equals("Long")) {
m3 = clazz.getDeclaredMethod(methodName.toString(), Long.class);
m3.setAccessible(false);
m3.invoke(obj, StringUtil.getNullLong(value));
} else if (columnType.equals("long")) {
m3 = clazz.getDeclaredMethod(methodName.toString(), long.class);
m3.setAccessible(false);
m3.invoke(obj, StringUtil.getLongOfObj(value));
} else if (columnType.equals("float")) {
m3 = clazz.getDeclaredMethod(methodName.toString(), float.class);
m3.setAccessible(false);
m3.invoke(obj, StringUtil.getFloatOfObj(value));
} else if (columnType.equals("Double")) {
m3 = clazz.getDeclaredMethod(methodName.toString(), Double.class);
m3.setAccessible(false);
m3.invoke(obj, Double.parseDouble(value));
} else if (columnType.equals("double")) {
m3 = clazz.getDeclaredMethod(methodName.toString(), double.class);
m3.setAccessible(false);
m3.invoke(obj, StringUtil.getDoubleOfObj(value));
} else if (columnType.equals("boolean")) {
m3 = clazz.getDeclaredMethod(methodName.toString(), boolean.class);
m3.setAccessible(false);
m3.invoke(obj, StringUtil.getBooleanOfObj(value));
} else {
throw new ApiException("数据行" + columnName + "类型有误;类型为:" + columnType);
}
} catch (Exception e) {
e.printStackTrace();
logger.error("方法setColumnValue有错;错误原因:" + e.getMessage());
}
}
public static Boolean getExpressionResult(String expression) {
Boolean result = false;
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
result = (Boolean) engine.eval(expression);
} catch (Exception e) {
logger.error("转换运算表达式有误;error:" + e.getMessage() + "expression=" + expression);
result = false;
}
return result;
}
/**
* 自动将字符串补足N位 ,如1111——》0000001111
*
* @param kh
* @return
*/
public static String fixToNum(String kh, int num) {
if (StringUtil.isNotEmpty(kh) && kh.length() < num) {
for (int i = num - kh.length(); i > 0; i--) {
kh = "0" + kh;
}
}
return kh;
}
public static String getChineseNumber(Integer number) {
return CHINESE_NUMBER[number - 1];
}
/**
* 0和负数视为null
*
* @return
*/
public static Float getNullFloat(Float value) {
if (value != null && value > 0f) {
return value;
} else {
return null;
}
}
/**
* 获取两位小数
*
* @return
*/
public static String formartFloat(Float value) {
if (value != null) {
return decimalFormat.format(value);
} else {
return null;
}
}
public static String formart4DecimalFloat(Float value) {
if (value != null) {
String str = DECIMAL_FORMAT_FOUR.format(value);
if (str.length() > 0) {
if (str.substring(str.length() - 4, str.length()).equals("0000")) {
str = str.substring(0, str.length() - 5);
} else if (str.substring(str.length() - 3, str.length()).equals("000")) {
str = str.substring(0, str.length() - 3);
} else if (str.substring(str.length() - 2, str.length()).equals("00")) {
str = str.substring(0, str.length() - 2);
} else if (str.substring(str.length() - 1, str.length()).equals("0")) {
str = str.substring(0, str.length() - 1);
}
}
return str.replace("0.0000", "0");
} else {
return null;
}
}
// 根据经纬度计算两个点之间的直线距离(单位:米)
public static double getDistance(double lat1, double lng1, double lat2, double lng2) {
double a = rad(lat1) - rad(lat2);
double b = rad(lng1) - rad(lng2);
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
+ Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.pow(Math.sin(b / 2), 2)));
s = s * EARTH_RADIUS;
s = Math.round(s * 10000d) / 10000d;
s = s * 1000;
return s;
}
private static double rad(double d) {
return d * Math.PI / 180.0;
}
public static String makeDistanceStr(Double distance) {
if (distance >= 1000D) {
return StringUtil.formartDecimal(distance / 1000) + "km";
}
return StringUtil.formartDecimal(distance) + "m";
}
/**
* 两个数字相乘 d1*d2
*
* @param d1
* @param d2
* @return
*/
public static double mul(String d1, String d2) {
try {
BigDecimal b1 = new BigDecimal(d1);
BigDecimal b2 = new BigDecimal(d2);
return b1.multiply(b2).doubleValue();
} catch (Exception e) {
return 0;
}
}
/**
* 获取一定长度的随机字符串
*
* @param length
* 指定字符串长度
* @return 一定长度的字符串
*/
public static String getRandomStringByLength(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 校验经纬度坐标格式
*
* @param coordinate
* @return
*/
public static boolean isRegex(String coordinate) {
String regex = "^((-)?\\d*(\\.)?\\d*)[,]((-)?\\d*(\\.)?\\d*)$";
boolean result = Pattern.compile(regex).matcher(coordinate).find();
if (!result) {
throw new RuntimeException("经纬度坐标不正确:coordinate:" + coordinate);
}
return result;
}
/**
* 生成序号,当前时间前八位,加上随机的字符
*
* @return
*/
public static String getSerialNumber() {
return DateUtil.dateToCompactString(DateUtil.getCurrentTimeDate()) + StringUtil.get6RandomStr();
}
public static String geImgtHttpUrl(String imgUrl) {
if (StringUtil.isNullOrEmpty(imgUrl)) {
return "";
}
if (imgUrl.length() > 500) {
return "";
}
if (imgUrl.indexOf("http://") > -1 || imgUrl.indexOf("https://") > -1) {
return imgUrl;
}
return "";
}
public static String length50(String content) {
String result = content;
if (StringUtil.isNullOrEmpty(content)) {
return "";
}
if (content.length() >= 60) {
result = content.substring(0, 49) + "...";
}
return result;
}
public static String length1000(String content) {
String result = content;
if (StringUtil.isNullOrEmpty(content)) {
return "";
}
if (content.length() >= 1000) {
result = content.substring(0, 500) + "...";
}
return result;
}
public static String clearInvisibleCharacter(String content) {
if (isNotEmpty(content)) {
char[] contentCharArr = content.toCharArray();
for (int i = 0; i < contentCharArr.length; i++) {
if (contentCharArr[i] < 0x20 || contentCharArr[i] == 0x7F) {
contentCharArr[i] = 0x20;
}
}
return new String(contentCharArr);
}
return "";
}
public static String removeHtml(String content) {
String regExHtml = "<[^>]+>"; // 定义HTML标签的正则表达式
Pattern pHtml = Pattern.compile(regExHtml, Pattern.CASE_INSENSITIVE);
Matcher mHtml = pHtml.matcher(content);
content = mHtml.replaceAll("");
return content;
}
/**
* 判断身份证格式
*
* @param idNum
* @return
*/
public static Map<String, Object> getIdNumberInfo(String idNum) {
Map<String, Object> idNumberMap = new HashMap<String, Object>();
if (isNullOrEmpty(idNum)) {
idNumberMap.put("isCorrect", false);
return idNumberMap;
}
boolean isCorrect = true;
// 中国公民身份证格式:长度为15或18位,最后一位可以为字母
Pattern idNumPattern = Pattern.compile("(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])");
// 格式验证
if (!idNumPattern.matcher(idNum).matches())
isCorrect = false;
// 合法性验证
int year = 0;
int month = 0;
int day = 0;
if (idNum.length() == 15) {
// 一代身份证
System.out.println("一代身份证:" + idNum);
// 提取身份证上的前6位以及出生年月日
Pattern birthDatePattern = Pattern.compile("\\d{6}(\\d{2})(\\d{2})(\\d{2}).*");
Matcher birthDateMather = birthDatePattern.matcher(idNum);
if (birthDateMather.find()) {
year = Integer.valueOf("19" + birthDateMather.group(1));
month = Integer.valueOf(birthDateMather.group(2));
day = Integer.valueOf(birthDateMather.group(3));
}
} else if (idNum.length() == 18) {
// 二代身份证
System.out.println("二代身份证:" + idNum);
// 提取身份证上的前6位以及出生年月日
Pattern birthDatePattern = Pattern.compile("\\d{6}(\\d{4})(\\d{2})(\\d{2}).*");
Matcher birthDateMather = birthDatePattern.matcher(idNum);
if (birthDateMather.find()) {
year = Integer.valueOf(birthDateMather.group(1));
month = Integer.valueOf(birthDateMather.group(2));
day = Integer.valueOf(birthDateMather.group(3));
}
}
// 年份判断,100年前至今
Calendar cal = Calendar.getInstance();
// 当前年份
int currentYear = cal.get(Calendar.YEAR);
if (year <= currentYear - 100 || year > currentYear)
isCorrect = false;
// 月份判断
if (month < 1 || month > 12)
isCorrect = false;
// 日期判断
// 计算月份天数
int dayCount = 31;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
dayCount = 31;
break;
case 2:
// 2月份判断是否为闰年
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
dayCount = 29;
break;
} else {
dayCount = 28;
break;
}
case 4:
case 6:
case 9:
case 11:
dayCount = 30;
break;
}
if (day < 1 || day > dayCount)
isCorrect = false;
try {
if (idNum.length() == 15) {
idNumberMap = getCarInfo15W(idNum);
} else if (idNum.length() == 18) {
idNumberMap = getCarInfo(idNum);
}
} catch (Exception e) {
isCorrect = false;
}
idNumberMap.put("isCorrect", isCorrect);
return idNumberMap;
}
/**
* 15位身份证的验证
*
* @param
* @throws Exception
*/
public static Map<String, Object> getCarInfo15W(String card) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
String fyear = "19" + card.substring(6, 8);// 年份
String fyue = card.substring(8, 10);// 月份
String fday = card.substring(10, 12);// 日
String usex = card.substring(14, 15);// 用户的性别
String sex;
if (Integer.parseInt(usex) % 2 == 0) {
sex = "2";
} else {
sex = "1";
}
Date date = new Date();// 得到当前的系统时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String year = format.format(date).substring(0, 4);// 当前年份
String yue = format.format(date).substring(5, 7);// 月份
// String fday = format.format(date).substring(8, 10);
int age = 0;
if (Integer.parseInt(yue) <= Integer.parseInt(fyue)) { //
age = Integer.parseInt(year) - Integer.parseInt(fyear) + 1;
} else {// 当前用户还没过生
age = Integer.parseInt(year) - Integer.parseInt(fyear);
}
map.put("age", age);
map.put("sex", sex);
map.put("birthday", fyear + "-" + fyue + "-" + fday);
return map;
}
/**
* 根据身份证的号码算出当前身份证持有者的性别和年龄 18位身份证
*
* @return
* @throws Exception
*/
public static Map<String, Object> getCarInfo(String CardCode) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
String fyear = CardCode.substring(6).substring(0, 4);// 得到年份
String fyue = CardCode.substring(10).substring(0, 2);// 得到月份
String fday = CardCode.substring(12).substring(0, 2);// 得到日
String sex;
if (Integer.parseInt(CardCode.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
sex = "2";
} else {
sex = "1";
}
Date date = new Date();// 得到当前的系统时间
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String year = format.format(date).substring(0, 4);// 当前年份
String yue = format.format(date).substring(5, 7);// 月份
// String day = format.format(date).substring(8, 10);
int age = 0;
if (Integer.parseInt(yue) <= Integer.parseInt(fyue)) { //
age = Integer.parseInt(year) - Integer.parseInt(fyear) + 1;
} else {// 当前用户还没过生
age = Integer.parseInt(year) - Integer.parseInt(fyear);
}
map.put("age", age);
map.put("sex", sex);
map.put("birthday", fyear + "-" + fyue + "-" + fday);
return map;
}
public static String encodeBASE64(String s) {
if (s == null)
return null;
try {
return new String(Base64.encodeBase64(s.getBytes()), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
// return Base64.encodeBase64String(s.getBytes());
// return (new BASE64Encoder()).encode(s.getBytes());
}
public static String getPinYinHeadChar(String str) {
String convert = "";
for (int j = 0; j < str.length(); j++) {
char word = str.charAt(j);
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if (pinyinArray != null) {
convert += pinyinArray[0].charAt(0);
} else {
convert += word;
}
}
return convert;
}
/**
* 取出html代码中的网络图片
*
* @author cfq
* @param content
* @return
*/
public static List<String> getStringImgs(String content) {
List<String> result = new ArrayList<>();
if (StringUtil.isNullOrEmpty(content)) {
return result;
}
Pattern p = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
Matcher m = p.matcher(content);
while (m.find()) {
String img = StringUtil.getNullStr(m.group(1));
if (StringUtil.isNotEmpty(img)) {
result.add(img);
}
}
return result;
}
/**
* 替换字符串内容
*
* @author cfq
* @param content
* @param ordStr
* @param newStr
* @return
*/
public static String replace(String content, String ordStr, String newStr) {
if (StringUtil.isNullOrEmpty(content)) {
return "";
}
return content.replace(ordStr, newStr);
}
public static Integer formartBigInteger(BigInteger bigInteger) {
return bigInteger == null ? 0 : bigInteger.intValue();
}
public static String getCode(String code, String currentCode) {
if (StringUtil.isNullOrEmpty(currentCode)) {
return code + "0001";
}
int length = currentCode.length();
int index = 4 - length % 4;
String zeroStr = "";
while (index > 0) {
zeroStr = zeroStr + "0";
index--;
}
return zeroStr + currentCode;
}
public static JSONObject getTimeJson(String month, JSONObject termJson) {
String start = DateUtil.getMonthStartDatetime(month);
String end = DateUtil.getMonthEndDatetime(month);
String termStart = DateUtil.dateToString(termJson.getDate("weekbegin"), DateUtil.DATE_YYYYMM);
String termEnd = DateUtil.dateToString(termJson.getDate("weekend"), DateUtil.DATE_YYYYMM);
if (month.equals(termStart)) {
start = DateUtil.formatDate(termJson.getDate("weekbegin"));
} else if (month.equals(termEnd)) {
end = DateUtil.formatDate(termJson.getDate("weekend"));
}
JSONObject timeJson = new JSONObject();
timeJson.put("start", DateUtil.stringToDate(start, DateUtil.NORMAL_DATE_FORMAT));
timeJson.put("end", DateUtil.stringToDate(end, DateUtil.NORMAL_DATE_FORMAT));
return timeJson;
}
/**
* 将带有emoji字符的字符串转换成可见字符标识
*/
public static String escape(String src) {
if (StringUtils.isBlank(src)) {
return src;
}
int cpCount = src.codePointCount(0, src.length());
int firCodeIndex = src.offsetByCodePoints(0, 0);
int lstCodeIndex = src.offsetByCodePoints(0, cpCount - 1);
StringBuilder sb = new StringBuilder(src.length());
for (int index = firCodeIndex; index <= lstCodeIndex; index++) {
int codepoint = src.codePointAt(index);
if (isEmojiCharacter(codepoint)) {
String hash = Integer.toHexString(codepoint);
sb.append(unicode_separator).append(hash.length()).append(unicode_prefix).append(separator)
.append(hash);
// hash 长度,4位1个字节
index += (hash.length() - 1) / 4;
} else {
sb.append((char) codepoint);
}
}
return sb.toString();
}
/** 解析可见字符标识字符串 */
public static String reverse(String src) {
// 查找对应编码的标识位
if (StringUtils.isBlank(src)) {
return src;
}
StringBuilder sb = new StringBuilder(src.length());
char[] sourceChar = src.toCharArray();
int index = 0;
while (index < sourceChar.length) {
if (sourceChar[index] == unicode_separator) {
if (index + 6 >= sourceChar.length) {
sb.append(sourceChar[index]);
index++;
continue;
}
// 自已的格式,与通用unicode格式不能互转
if (sourceChar[index + 1] >= '4' && sourceChar[index + 1] <= '6'
&& sourceChar[index + 2] == unicode_prefix && sourceChar[index + 3] == separator) {
int length = Integer.parseInt(String.valueOf(sourceChar[index + 1]));
char[] hexchars = new char[length]; // 创建一个4至六位的数组,来存储uncode码的HEX值
for (int j = 0; j < length; j++) {
char ch = sourceChar[index + 4 + j];// 4位识别码
if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f')) {
hexchars[j] = ch;
} else { // 字符范围不对
sb.append(sourceChar[index]);
index++;
break;
}
}
sb.append(Character.toChars(Integer.parseInt(new String(hexchars), 16)));
index += (4 + length);// 4位前缀+4-6位字符码
} else if (sourceChar[index + 1] == unicode_prefix) { // 通用字符的反转
// 因为第二平面之上的,已经采用了我们自己转码格式,所以这里是固定的长度4
char[] hexchars = new char[4];
for (int j = 0; j < 4; j++) {
char ch = sourceChar[index + 2 + j]; // 两位识别码要去掉
if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f')) {
hexchars[j] = ch; // 4位识别码
} else { // 字符范围不对
sb.append(sourceChar[index]);
index++;
break;
}
sb.append(Character.toChars(Integer.parseInt(String.valueOf(hexchars), 16)));
index += (2 + 4);// 2位前缀+4位字符码
}
} else {
sb.append(sourceChar[index]);
index++;
continue;
}
} else {
sb.append(sourceChar[index]);
index++;
continue;
}
}
return sb.toString();
}
public static String filter(String src) {
if (src == null) {
return null;
}
int cpCount = src.codePointCount(0, src.length());
int firCodeIndex = src.offsetByCodePoints(0, 0);
int lstCodeIndex = src.offsetByCodePoints(0, cpCount - 1);
StringBuilder sb = new StringBuilder(src.length());
for (int index = firCodeIndex; index <= lstCodeIndex;) {
int codepoint = src.codePointAt(index);
if (!isEmojiCharacter(codepoint)) {
System.err.println("codepoint:" + Integer.toHexString(codepoint));
sb.append((char) codepoint);
}
index += ((Character.isSupplementaryCodePoint(codepoint)) ? 2 : 1);
}
return sb.toString();
}
private static boolean isEmojiCharacter(int codePoint) {
return (codePoint >= 0x2600 && codePoint <= 0x27BF) // 杂项符号与符号字体
|| codePoint == 0x303D || codePoint == 0x2049 || codePoint == 0x203C
|| (codePoint >= 0x2000 && codePoint <= 0x200F)//
|| (codePoint >= 0x2028 && codePoint <= 0x202F)//
|| codePoint == 0x205F //
|| (codePoint >= 0x2065 && codePoint <= 0x206F)//
/* 标点符号占用区域 */
|| (codePoint >= 0x2100 && codePoint <= 0x214F)// 字母符号
|| (codePoint >= 0x2300 && codePoint <= 0x23FF)// 各种技术符号
|| (codePoint >= 0x2B00 && codePoint <= 0x2BFF)// 箭头A
|| (codePoint >= 0x2900 && codePoint <= 0x297F)// 箭头B
|| (codePoint >= 0x3200 && codePoint <= 0x32FF)// 中文符号
|| (codePoint >= 0xD800 && codePoint <= 0xDFFF)// 高低位替代符保留区域
|| (codePoint >= 0xE000 && codePoint <= 0xF8FF)// 私有保留区域
|| (codePoint >= 0xFE00 && codePoint <= 0xFE0F)// 变异选择器
|| codePoint >= 0x10000; // Plane在第二平面以上的,char都不可以存,全部都转
}
/**
* 功能: 多个参数是否都不为 null、""、 " ".<br/>
* date: 2017年6月20日 下午4:03:01 <br/>
*
* @author zxguan_star@163.com
* @param params
* @return
*/
public static String splitByLine(String... params) {
// 数params是被作为一个数组对待的
if (null == params || params.length == 0) {
return "";
}
StringBuffer result = new StringBuffer();
int i = 0;
for (String param : params) {
i = i + 1;
if (StringUtils.isBlank(param)) {
if (i == params.length) {
result.append(param);
} else {
result.append(param).append("_");
}
}
}
return result.toString();
}
public static Integer getRandomInt(Integer num) {
int result = 0;
Random rand = new Random();
result = rand.nextInt(num);
return result;
}
/**
* 保留小数点后几位
*
* @param pointNumber
* @param number
* @return
*/
public static Double getDecimalPoint(int pointNumber, Double number) {
return new BigDecimal(number).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 判断字符串中是否包含中文
*
* @param str
* 待校验字符串 @ 是否为中文
* @warn 不能校验是否为中文标点符号
*/
public static boolean isContainChinese(String str) {
Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}
public static String removeSpecialStr(String content) {
String str = "";
if (StringUtil.isNotEmpty(content) && content.length() > 0) {
char[] contentCharArr = content.toCharArray();
for (int i = 0; i < contentCharArr.length; i++) {
if ((contentCharArr[i] < 0x20 || contentCharArr[i] == 0x7F) && contentCharArr[i] != 0x0A
&& contentCharArr[i] != 0x0D) {
contentCharArr[i] = 0x20;
}
}
str = new String(contentCharArr);
str = str.replaceAll(
"/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g",
"");
}
return StringUtil.removeSpecialString(StringUtil.reverse(str));
}
/***
* 接口: 功能描述: 根据子孙的code得到所有直系父code的list
*
* @param currentCode
* 1
* @return : java.util.List<java.lang.String>
* @author : qmm
* @date : 2019-06-20 15:13
*/
public static List<String> getParentCodeList(String currentCode) {
List<String> parentCodes = new ArrayList<>();
int level = currentCode.length() / 4;
for (int i = 1; i < level; i++) {
int number = i * 4;
String parentCode = currentCode.substring(0, number);
parentCodes.add(parentCode);
}
return parentCodes;
}
public static List<String> getMonthStr(String startTime, String endTime) {
List<String> listMonth = new ArrayList<>();
List<String> monthList = DateUtil.listMonthBetweenStartTimeAndEndTime(startTime, endTime);
String month1 = "";
for (int i = 0; i < monthList.size(); i++) {
String str = monthList.get(i);
month1 = StringUtil.getSubstringStr(str, 5, 7);// 两位
String month2 = month1.substring(0, 1);// 一位(个位)
String substring = month1.substring(1);
if (month2.equals("0")) {
listMonth.add(substring);
} else {
listMonth.add(month1);
}
}
return listMonth;
}
/**
* 返回wx前缀的appid字符串
*
* @param appid
* @return
*/
public static String getNullWxAppid(String appid) {
if (StringUtil.isNotEmpty(appid) && ("/" + appid).indexOf("/wx") > -1) {
return appid;
}
return "wx" + StringUtil.getRandomCharAndNumr(16);
}
/**
* 格式化字符,去除特殊字符
*
* @param s
* @return
*/
public static String fomartSpecialString(String s) {
String dest = "";
if (s != null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n|$|%|!|>|<|`");
Matcher m = p.matcher(s);
dest = m.replaceAll("");
}
return dest;
}
public static String getLimitedLengthStr(String str) {
if (StringUtil.isNullOrEmpty(str)) {
return "";
}
// 最大截取10000字符
if (str.length() > 10000) {
return str.substring(0,10000);
}
return str;
}
public static Boolean checkPassword(String password) {
if (StringUtil.isNullOrEmpty(password) || password.length() < 6 || password.length() > 18) {
return false;
}
if(!password.matches("\\w+")){
return false;
}
Pattern p1= Pattern.compile("[a-z]+");
Pattern p2= Pattern.compile("[A-Z]+");
Pattern p3= Pattern.compile("[0-9]+");
Matcher m=p1.matcher(password);
if(!m.find()) {
return false;
}
m.reset().usePattern(p2);
if(!m.find()) {
return false;
}
m.reset().usePattern(p3);
if(!m.find()) {
return false;
}
return true;
}
/**
* 过滤表情符号
* @param str
* @return
*/
public static String fomartEmojiString(String str) {
try {
Pattern pattern = Pattern.compile(unicodeReg);
StringBuilder reBuffer = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
String temp = String.valueOf(c);
Matcher matcher = pattern.matcher(temp);
if (matcher.find()) {
reBuffer.append(temp);
}
}
return reBuffer.toString();
} catch (Exception e) {
logger.error("转换表情符号出错"+e);
return "";
}
}
public final static String unicodeReg = "[" +
"\u4E00-\u9FBF" +//:CJK 统一表意符号 (CJK Unified Ideographs)
"\u4DC0-\u4DFF" +//:易经六十四卦符号 (Yijing Hexagrams Symbols)
"\u0000-\u007F" +//:C0控制符及基本拉丁文 (C0 Control and Basic Latin)
"\u0080-\u00FF" +//:C1控制符及拉丁:补充-1 (C1 Control and Latin 1 Supplement)
"\u0100-\u017F" +//:拉丁文扩展-A (Latin Extended-A)
"\u0180-\u024F" +//:拉丁文扩展-B (Latin Extended-B)
"\u0250-\u02AF" +//:国际音标扩展 (IPA Extensions)
"\u02B0-\u02FF" +//:空白修饰字母 (Spacing Modifiers)
"\u0300-\u036F" +//:结合用读音符号 (Combining Diacritics Marks)
"\u0370-\u03FF" +//:希腊文及科普特文 (Greek and Coptic)
"\u0400-\u04FF" +//:西里尔字母 (Cyrillic)
"\u0500-\u052F" +//:西里尔字母补充 (Cyrillic Supplement)
"\u0530-\u058F" +//:亚美尼亚语 (Armenian)
"\u0590-\u05FF" +//:希伯来文 (Hebrew)
"\u0600-\u06FF" +//:阿拉伯文 (Arabic)
"\u0700-\u074F" +//:叙利亚文 (Syriac)
"\u0750-\u077F" +//:阿拉伯文补充 (Arabic Supplement)
"\u0780-\u07BF" +//:马尔代夫语 (Thaana)
//"\u07C0-\u077F"+//:西非书面语言 (N'Ko)
"\u0800-\u085F" +//:阿维斯塔语及巴列维语 (Avestan and Pahlavi)
"\u0860-\u087F" +//:Mandaic
"\u0880-\u08AF" +//:撒马利亚语 (Samaritan)
"\u0900-\u097F" +//:天城文书 (Devanagari)
"\u0980-\u09FF" +//:孟加拉语 (Bengali)
"\u0A00-\u0A7F" +//:锡克教文 (Gurmukhi)
"\u0A80-\u0AFF" +//:古吉拉特文 (Gujarati)
"\u0B00-\u0B7F" +//:奥里亚文 (Oriya)
"\u0B80-\u0BFF" +//:泰米尔文 (Tamil)
"\u0C00-\u0C7F" +//:泰卢固文 (Telugu)
"\u0C80-\u0CFF" +//:卡纳达文 (Kannada)
"\u0D00-\u0D7F" +//:德拉维族语 (Malayalam)
"\u0D80-\u0DFF" +//:僧伽罗语 (Sinhala)
"\u0E00-\u0E7F" +//:泰文 (Thai)
"\u0E80-\u0EFF" +//:老挝文 (Lao)
"\u0F00-\u0FFF" +//:藏文 (Tibetan)
"\u1000-\u109F" +//:缅甸语 (Myanmar)
"\u10A0-\u10FF" +//:格鲁吉亚语 (Georgian)
"\u1100-\u11FF" +//:朝鲜文 (Hangul Jamo)
"\u1200-\u137F" +//:埃塞俄比亚语 (Ethiopic)
"\u1380-\u139F" +//:埃塞俄比亚语补充 (Ethiopic Supplement)
"\u13A0-\u13FF" +//:切罗基语 (Cherokee)
"\u1400-\u167F" +//:统一加拿大土著语音节 (Unified Canadian Aboriginal Syllabics)
"\u1680-\u169F" +//:欧甘字母 (Ogham)
"\u16A0-\u16FF" +//:如尼文 (Runic)
"\u1700-\u171F" +//:塔加拉语 (Tagalog)
"\u1720-\u173F" +//:Hanunóo
"\u1740-\u175F" +//:Buhid
"\u1760-\u177F" +//:Tagbanwa
"\u1780-\u17FF" +//:高棉语 (Khmer)
"\u1800-\u18AF" +//:蒙古文 (Mongolian)
"\u18B0-\u18FF" +//:Cham
"\u1900-\u194F" +//:Limbu
"\u1950-\u197F" +//:德宏泰语 (Tai Le)
"\u1980-\u19DF" +//:新傣仂语 (New Tai Lue)
"\u19E0-\u19FF" +//:高棉语记号 (Kmer Symbols)
"\u1A00-\u1A1F" +//:Buginese
"\u1A20-\u1A5F" +//:Batak
"\u1A80-\u1AEF" +//:Lanna
"\u1B00-\u1B7F" +//:巴厘语 (Balinese)
"\u1B80-\u1BB0" +//:巽他语 (Sundanese)
"\u1BC0-\u1BFF" +//:Pahawh Hmong
"\u1C00-\u1C4F" +//:雷布查语(Lepcha)
"\u1C50-\u1C7F" +//:Ol Chiki
"\u1C80-\u1CDF" +//:曼尼普尔语 (Meithei/Manipuri)
"\u1D00-\u1D7F" +//:语音学扩展 (Phone tic Extensions)
"\u1D80-\u1DBF" +//:语音学扩展补充 (Phonetic Extensions Supplement)
"\u1DC0-\u1DFF" +//结合用读音符号补充 (Combining Diacritics Marks Supplement)
"\u1E00-\u1EFF" +//:拉丁文扩充附加 (Latin Extended Additional)
"\u1F00-\u1FFF" +//:希腊语扩充 (Greek Extended)
"\u2000-\u206F" +//:常用标点 (General Punctuation)
"\u2070-\u209F" +//:上标及下标 (Superscripts and Subscripts)
"\u20A0-\u20CF" +//:货币符号 (Currency Symbols)
"\u20D0-\u20FF" +//:组合用记号 (Combining Diacritics Marks for Symbols)
"\u2100-\u214F" +//:字母式符号 (Letterlike Symbols)
"\u2150-\u218F" +//:数字形式 (Number Form)
"\u2190-\u21FF" +//:箭头 (Arrows)
"\u2200-\u22FF" +//:数学运算符 (Mathematical Operator)
"\u2300-\u23FF" +//:杂项工业符号 (Miscellaneous Technical)
"\u2400-\u243F" +//:控制图片 (Control Pictures)
"\u2440-\u245F" +//:光学识别符 (Optical Character Recognition)
"\u2460-\u24FF" +//:封闭式字母数字 (Enclosed Alphanumerics)
"\u2500-\u257F" +//:制表符 (Box Drawing)
"\u2580-\u259F" +//:方块元素 (Block Element)
"\u25A0-\u25FF" +//:几何图形 (Geometric Shapes)
"\u2600-\u26FF" +//:杂项符号 (Miscellaneous Symbols)
"\u2700-\u27BF" +//:印刷符号 (Dingbats)
"\u27C0-\u27EF" +//:杂项数学符号-A (Miscellaneous Mathematical Symbols-A)
"\u27F0-\u27FF" +//:追加箭头-A (Supplemental Arrows-A)
"\u2800-\u28FF" +//:盲文点字模型 (Braille Patterns)
"\u2900-\u297F" +//:追加箭头-B (Supplemental Arrows-B)
"\u2980-\u29FF" +//:杂项数学符号-B (Miscellaneous Mathematical Symbols-B)
"\u2A00-\u2AFF" +//:追加数学运算符 (Supplemental Mathematical Operator)
"\u2B00-\u2BFF" +//:杂项符号和箭头 (Miscellaneous Symbols and Arrows)
"\u2C00-\u2C5F" +//:格拉哥里字母 (Glagolitic)
"\u2C60-\u2C7F" +//:拉丁文扩展-C (Latin Extended-C)
"\u2C80-\u2CFF" +//:古埃及语 (Coptic)
"\u2D00-\u2D2F" +//:格鲁吉亚语补充 (Georgian Supplement)
"\u2D30-\u2D7F" +//:提非纳文 (Tifinagh)
"\u2D80-\u2DDF" +//:埃塞俄比亚语扩展 (Ethiopic Extended)
"\u2E00-\u2E7F" +//:追加标点 (Supplemental Punctuation)
"\u2E80-\u2EFF" +//:CJK 部首补充 (CJK Radicals Supplement)
"\u2F00-\u2FDF" +//:康熙字典部首 (Kangxi Radicals)
"\u2FF0-\u2FFF" +//:表意文字描述符 (Ideographic Description Characters)
"\u3000-\u303F" +//:CJK 符号和标点 (CJK Symbols and Punctuation)
"\u3040-\u309F" +//:日文平假名 (Hiragana)
"\u30A0-\u30FF" +//:日文片假名 (Katakana)
"\u3100-\u312F" +//:注音字母 (Bopomofo)
"\u3130-\u318F" +//:朝鲜文兼容字母 (Hangul Compatibility Jamo)
"\u3190-\u319F" +//:象形字注释标志 (Kanbun)
"\u31A0-\u31BF" +//:注音字母扩展 (Bopomofo Extended)
"\u31C0-\u31EF" +//:CJK 笔画 (CJK Strokes)
"\u31F0-\u31FF" +//:日文片假名语音扩展 (Katakana Phonetic Extensions)
"\u3200-\u32FF" +//:封闭式 CJK 文字和月份 (Enclosed CJK Letters and Months)
"\u3300-\u33FF" +//:CJK 兼容 (CJK Compatibility)
"\u3400-\u4DBF" +//:CJK 统一表意符号扩展 A (CJK Unified Ideographs Extension A)
"\u4DC0-\u4DFF" +//:易经六十四卦符号 (Yijing Hexagrams Symbols)
"\u4E00-\u9FBF" +//:CJK 统一表意符号 (CJK Unified Ideographs)
"\uA000-\uA48F" +//:彝文音节 (Yi Syllables)
"\uA490-\uA4CF" +//:彝文字根 (Yi Radicals)
"\uA500-\uA61F" +//:Vai
"\uA660-\uA6FF" +//:统一加拿大土著语音节补充 (Unified Canadian Aboriginal Syllabics Supplement)
"\uA700-\uA71F" +//:声调修饰字母 (Modifier Tone Letters)
"\uA720-\uA7FF" +//:拉丁文扩展-D (Latin Extended-D)
"\uA800-\uA82F" +//:Syloti Nagri
"\uA840-\uA87F" +//:八思巴字 (Phags-pa)
"\uA880-\uA8DF" +//:Saurashtra
"\uA900-\uA97F" +//:爪哇语 (Javanese)
"\uA980-\uA9DF" +//:Chakma
"\uAA00-\uAA3F" +//:Varang Kshiti
"\uAA40-\uAA6F" +//:Sorang Sompeng
"\uAA80-\uAADF" +//:Newari
"\uAB00-\uAB5F" +//:越南傣语 (Vi?t Thái)
"\uAB80-\uABA0" +//:Kayah Li
"\uAC00-\uD7AF" +//:朝鲜文音节 (Hangul Syllables)
//"\uD800-\uDBFF"+//:High-half zone of UTF-16
//"\uDC00-\uDFFF"+//:Low-half zone of UTF-16
"\uE000-\uF8FF" +//:自行使用区域 (Private Use Zone)
"\uF900-\uFAFF" +//:CJK 兼容象形文字 (CJK Compatibility Ideographs)
"\uFB00-\uFB4F" +//:字母表达形式 (Alphabetic Presentation Form)
"\uFB50-\uFDFF" +//:阿拉伯表达形式A (Arabic Presentation Form-A)
"\uFE00-\uFE0F" +//:变量选择符 (Variation Selector)
"\uFE10-\uFE1F" +//:竖排形式 (Vertical Forms)
"\uFE20-\uFE2F" +//:组合用半符号 (Combining Half Marks)
"\uFE30-\uFE4F" +//:CJK 兼容形式 (CJK Compatibility Forms)
"\uFE50-\uFE6F" +//:小型变体形式 (Small Form Variants)
"\uFE70-\uFEFF" +//:阿拉伯表达形式B (Arabic Presentation Form-B)
"\uFF00-\uFFEF" +//:半型及全型形式 (Halfwidth and Fullwidth Form)
"\uFFF0-\uFFFF]";//:特殊 (Specials);
}
\ No newline at end of file
package com.spacetech.common.utils;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
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.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.common.exception.ApiException;
/**
* 模拟发送HTTP 请求的工具类
*
* @author yejianfei
*
*/
public class SubmitHttpRequestUtil {
private static Logger logger = LoggerFactory.getLogger(SubmitHttpRequestUtil.class);
public static void main(String[] args) {
String accessToken = "UJYjSbhaXh1RrFp-ncrwspH6gUE3P6Y0EWQJb2SbGVkLTIRZqJsvI385piJLiGVz7nInykaQaX-7YFbKhyat5Ix3v9EqgHLi6q-riuytsOlnToU9c0GheUPE6A_5uP-lW0MW5LQUl-1cagf4x-v2tDyQ2dZjfX-RLBV3-7qhdpfTjL7nwGO7p5Mx0yF26njMZI-Li9eAQhYZjcCONWNosw";
String mediaId = "16h3ovrZnLsfyAUWUQ2cqj16-TQ8JPDg4JUWnCCq2gyEN79H90wdezgqwzN9U36J3";
String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
// requestUrl =
// https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=UJYjSbhaXh1RrFp-ncrwspH6gUE3P6Y0EWQJb2SbGVkLTIRZqJsvI385piJLiGVz7nInykaQaX-7YFbKhyat5Ix3v9EqgHLi6q-riuytsOlnToU9c0GheUPE6A_5uP-lW0MW5LQUl-1cagf4x-v2tDyQ2dZjfX-RLBV3-7qhdpfTjL7nwGO7p5Mx0yF26njMZI-Li9eAQhYZjcCONWNosw&media_id=15MiPJnTq1NtYnrnKhSkyIw70SwOOYuRdcdbs6Z_uN64
// filePath = /mnt/work/weikedata/wxLocalResource6748989662492957044.jpeg
// https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=&media_id=
// downloadMedia(accessToken, mediaId, requestUrl, true);
String getUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=3xqCI5KM3A9GHkQcapi-tEC2FwmDHxC9hCqN1jU9tHSNAPGib5H1KFX1SCBH957UYiC2dNLk1y8Pm1kZwobcUHJlqstC-iIFeYBweI-JvIFz274vnMB_gvQbrMBa1xe04xqaekWVRsCgCsV8niQRhDfcfto3ktRM2nd3ylwNFhj5fIbKQPLZMXDRLZtoZsSTuc7Mdyb98ecwpqtPJ6c4iA&media_id=1ZFSTjSSgO6NmUfbhQhqYCZSO4ZXvY4uWrf3Zv94LS9zoiVPbuNFrHmPWL06q1fC9";
for (int i = 0; i < 2; i++) {
CloseableHttpClient client = getHttpClient();
HttpGet httpGet = new HttpGet(getUrl);
CloseableHttpResponse response = null;
try {
httpGet.setHeader("Accept-Encoding", "identity");
response = client.execute(httpGet);
Header[] headerList = response.getAllHeaders();
for (Header header : headerList) {
System.out.println("headerName=" + header.getName() + " headerValue=" + header.getValue());
}
HttpEntity entity = response.getEntity();
long fileLength = entity.getContentLength();
System.out.println("fileLength=" + fileLength);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static HttpURLConnection createPostConnection(String requestUrl)
throws MalformedURLException, IOException, ProtocolException {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("POST");
return conn;
}
public static HttpURLConnection createGetConnection(String requestUrl)
throws MalformedURLException, IOException, ProtocolException {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
return conn;
}
public static String createFileFromInputStream(String savePath, InputStream in, String filename)
throws IOException, FileNotFoundException {
String filePath = "";
StringBuffer responseMessage = new StringBuffer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[8096];
int len;
while ((len = in.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
// 生成文件
InputStream stream2 = new ByteArrayInputStream(baos.toByteArray());
BufferedInputStream bis = new BufferedInputStream(stream2);
if (StringUtil.isNullOrEmpty(filename)) {
throw new ApiException("微信下载媒体文件失败 ,filePath = " + filePath + " filename=" + filename);
}
// 根据内容类型获取扩展名
// String fileExt = "jpg";
// 将mediaId作为文件名
filePath = savePath + filename;
FileOutputStream fos = new FileOutputStream(new File(filePath));
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1) {
responseMessage.append((char) size);
fos.write(buf, 0, size);
}
stream2.close();
fos.close();
bis.close();
return filePath;
}
public static JSONObject submitPost(String url, String paramContent) {
return submitPost(url, paramContent, null);
}
/**
* java.net实现 HTTP POST方法提交
*
* @param url
* @param paramContent
* @return
*/
public static JSONObject submitPost(String url, String paramContent, Map<String, String> requestHeaderMap) {
CloseableHttpClient client = getHttpClient();
HttpPost post = new HttpPost(url);
String responseString = "";
CloseableHttpResponse response = null;
try {
setRequestHeader(requestHeaderMap, post);
if (paramContent != null) {
post.setEntity(new StringEntity(paramContent, "utf-8"));
}
response = client.execute(post);
responseString = EntityUtils.toString(response.getEntity(), "utf-8");
return JSON.parseObject(StringUtil.unicodeToString(responseString));
} catch (Exception e) {
logger.error("submitPost ERROR , url = " + url + " ,param = " + paramContent + ",responseString="
+ responseString, e);
return null;
} finally {
closeConnection(client, post, response);
}
}
public static JSONObject submitGetRequest(String url) {
return submitGetRequest(url, null);
}
/**
* 提交GET 请求到服务器
*
* @param url
* @return
*/
public static JSONObject submitGetRequest(String url, Map<String, String> requestHeaderMap) {
CloseableHttpClient client = getHttpClient();
HttpGet get = new HttpGet(url);
CloseableHttpResponse response = null;
String responseString = "";
try {
setRequestHeader(requestHeaderMap, get);
response = client.execute(get);
responseString = EntityUtils.toString(response.getEntity(), "utf-8");
return JSON.parseObject(StringUtil.unicodeToString(responseString));
} catch (java.net.ConnectException e) {
logger.error("submitGetRequest 网络异常 请求url=" + url + "*responseMessage=" + responseString, e);
return null;
} catch (Exception e) {
logger.error("submitGetRequest 处理错误 请求url=" + url + "*responseMessage=" + responseString, e);
return null;
} finally {
closeConnection(client, get, response);
}
}
public static void closeConnection(CloseableHttpClient client, HttpPost post, CloseableHttpResponse response) {
try {
if (response != null) {
response.close();
}
post.releaseConnection();
client.close();
} catch (Exception e) {
// e.printStackTrace();
}
}
public static void closeConnection(CloseableHttpClient client, HttpGet get, CloseableHttpResponse response) {
try {
if (response != null) {
response.close();
}
get.releaseConnection();
client.close();
} catch (Exception e) {
// e.printStackTrace();
}
}
private static CloseableHttpClient getHttpClient() {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(200);// 连接池最大并发连接数
cm.setDefaultMaxPerRoute(60);// 单路由最大并发数
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
return httpClient;
}
private static void setRequestHeader(Map<String, String> requestHeaderMap, HttpPost post) {
if (requestHeaderMap != null) {
Iterator iter = requestHeaderMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
if (entry.getValue() != null) {
post.setHeader(entry.getKey(), entry.getValue());
}
}
}
}
private static void setRequestHeader(Map<String, String> requestHeaderMap, HttpGet get) {
if (requestHeaderMap != null) {
Iterator iter = requestHeaderMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
if (entry.getValue() != null) {
get.setHeader(entry.getKey(), entry.getValue());
}
}
}
}
}
package com.spacetech.common.utils;
public class UtilConstant {
public static final String arrive_late_hhmmss = "07:50:00";
public static final String leave_early_hhmmss = "16:30:00";
/**
* 上传的各类文件存在的文件夹名称
*/
public static final String FOLDER_LOGO = "logo";// 每个学校的logo,文件夹
public static final String FOLDER_XXJJ = "xxjj";// 每个学校简介
public static final String FOLDER_TEACHERZP = "techaerzp";// 每个学校新闻动态
public static final String FOLDER_NEWS = "news";// 公司网站新闻
public static final String FOLDER_VIDEOFMS = "videofms";// 公司网站视频封面
public static final String FOLDER_VIDEOS = "videos";// 公司网站视频
public static final String FOLDER_BJSJ = "bjsj";// 每个班级图标
public static final String FOLDER_BJDT = "bjdt";// 每个班级图标
public static final String FOLDER_YQDT = "yqdt";// 每个班级图标
public static final String FOLDER_CYTD = "cytd";// 创意空间上传的图片
public static final String FOLDER_XSZP = "xszp";// 创意空间上传的图片
public static final String FOLDER_PRIZE = "prize";// 创意空间上传的图片
public static final String FOLDER_AWARD = "award";// 创意空间上传的图片
public static final String GHHD_THEME_PIC = "ghhd";// 运营活动上传的图片
// public static final String WEIKE_FILE = "F:/00/";// 微课上传文件目录
public static final String WEIKE_FILE = "/mnt/work/weikedata/";//
// 微课上传文件目录
public static final int XXJJ_TYPE = 98;// 学校简介的wlzyType
public static final int SUPERADMIN = 1;// 初始化管理员的标识
public static final String[] MRCP_TYPE = new String[] { "早餐", "早点", "午餐", "午点", "晚餐", "" };
public static final String[] WEEK_DAY = new String[] { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };
public static final String[] YQDT_TYPE_CH = new String[] { "招生公告", "园所新闻", "育儿知识", "家长感言" };
public static final int[] YQDT_TYPE = new int[] { 2, 3, 7, 8 };
/*** 系统参数 start ****/
/**
* 域名
*/
public static final String DOMAIN_NAME = "401";
/*** 系统参数 end ****/
/*** 消息参数 start ****/
public static final String USER_ROLE_SUPERADMIN = "superAdmin";
public static final String USER_ROLE_USER = "user";
public static final String USER_ROLE_ADMIN = "admin";
public static final String USER_ROLE_LEADER = "leader";
public static final String USER_ROLE_ASSISTANT = "assistant";
/*** 消息参数 end ****/
public static final String CRLF_RN = "\r\n";
public static final int SHCOOL_NOTIC_TYPE = 1;// 全校通知
public static final int CLASS_NOTIC_TYPE = 2;// 班级通知
public static final int KINDLY_REMINDER_TYPE = 3;// 温馨提示
public static final int TEACHER_NOTIC_TYPE = 4;// 教师通知
public static final int HISTORY_NOTIC_TYPE = 5;// 教师通知
public static final int Comment_HOMEWORK_TYPE = 1;// 作业评语
}
package com.spacetech.common.utils;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.sun.xml.txw2.annotation.XmlCDATA;
@XmlRootElement(name = "xml")
public class WeChatReqBean {
private String toUserName;
private String fromUserName;
private Long createTime;
private String msgType;
private String content;
private String event;
private String eventKey;
private String picUrl;
private String mediaId;
private Double location_X;
private Double location_Y;
private Integer scale;
private String label;
private String msgId;
private String recognition;
private String failtime;// 失败发生时间
private String failreason;// 认证失败的原有
private String expiredtime;// 过期时间
private String infoType;//开放平台 事件类型
private String appId;//公众帐号第三方平台
private String componentVerifyTicket;//出于安全考虑,在第三方平台创建审核通过后,微信服务器每隔10分钟会向第三方的消息接收地址推送一次component_verify_ticket,用于获取第三方平台接口调用凭据
private String authorizerAppid;//公众号appid
private String authorizationCode;//授权码(code)
private String authorizationCodeExpiredTime;//过期时间
public String getFailtime() {
return failtime;
}
@XmlCDATA
@XmlElement(name = "FailTime")
public void setFailtime(String failtime) {
this.failtime = failtime;
}
public String getFailreason() {
return failreason;
}
@XmlCDATA
@XmlElement(name = "FailReason")
public void setFailreason(String failreason) {
this.failreason = failreason;
}
public String getExpiredtime() {
return expiredtime;
}
@XmlCDATA
@XmlElement(name = "ExpiredTime")
public void setExpiredtime(String expiredtime) {
this.expiredtime = expiredtime;
}
public String getEvent() {
return event;
}
@XmlCDATA
@XmlElement(name = "Event")
public void setEvent(String event) {
this.event = event;
}
public String getEventKey() {
return eventKey;
}
@XmlCDATA
@XmlElement(name = "EventKey")
public void setEventKey(String eventKey) {
this.eventKey = eventKey;
}
public String getToUserName() {
return toUserName;
}
@XmlCDATA
@XmlElement(name = "ToUserName")
public void setToUserName(String toUserName) {
this.toUserName = toUserName;
}
public String getFromUserName() {
return fromUserName;
}
@XmlCDATA
@XmlElement(name = "FromUserName")
public void setFromUserName(String fromUserName) {
this.fromUserName = fromUserName;
}
public Long getCreateTime() {
return createTime;
}
@XmlElement(name = "CreateTime")
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
public String getMsgType() {
return msgType;
}
@XmlCDATA
@XmlElement(name = "MsgType")
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public String getContent() {
return content;
}
@XmlCDATA
@XmlElement(name = "Content")
public void setContent(String content) {
this.content = content;
}
public Double getLocation_X() {
return location_X;
}
@XmlElement(name = "Location_X")
public void setLocation_X(Double location_X) {
this.location_X = location_X;
}
public Double getLocation_Y() {
return location_Y;
}
@XmlElement(name = "Location_Y")
public void setLocation_Y(Double location_Y) {
this.location_Y = location_Y;
}
public Integer getScale() {
return scale;
}
@XmlElement(name = "Scale")
public void setScale(Integer scale) {
this.scale = scale;
}
public String getLabel() {
return label;
}
@XmlCDATA
@XmlElement(name = "Label")
public void setLabel(String label) {
this.label = label;
}
public String getMsgId() {
return msgId;
}
@XmlElement(name = "MsgId")
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public String getPicUrl() {
return picUrl;
}
@XmlElement(name = "PicUrl")
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getMediaId() {
return mediaId;
}
@XmlElement(name = "MediaId")
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public String getRecognition() {
return recognition;
}
@XmlElement(name = "Recognition")
public void setRecognition(String recognition) {
this.recognition = recognition;
}
public String getInfoType() {
return infoType;
}
@XmlElement(name = "InfoType")
public void setInfoType(String infoType) {
this.infoType = infoType;
}
public String getAppId() {
return appId;
}
@XmlElement(name = "AppId")
public void setAppId(String appId) {
this.appId = appId;
}
public String getComponentVerifyTicket() {
return componentVerifyTicket;
}
@XmlElement(name = "ComponentVerifyTicket")
public void setComponentVerifyTicket(String componentVerifyTicket) {
this.componentVerifyTicket = componentVerifyTicket;
}
public String getAuthorizerAppid() {
return authorizerAppid;
}
@XmlElement(name = "AuthorizerAppid")
public void setAuthorizerAppid(String authorizerAppid) {
this.authorizerAppid = authorizerAppid;
}
public String getAuthorizationCode() {
return authorizationCode;
}
@XmlElement(name = "AuthorizationCode")
public void setAuthorizationCode(String authorizationCode) {
this.authorizationCode = authorizationCode;
}
public String getAuthorizationCodeExpiredTime() {
return authorizationCodeExpiredTime;
}
@XmlElement(name = "AuthorizationCodeExpiredTime")
public void setAuthorizationCodeExpiredTime(String authorizationCodeExpiredTime) {
this.authorizationCodeExpiredTime = authorizationCodeExpiredTime;
}
}
package com.spacetech.common.utils;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlRootElement(name = "xml")
public class WeChatRespBean {
private String toUserName;
private String fromUserName;
private Long createTime;
private String msgType;
private String content;
private Integer funcFlag = 0;
public String getToUserName() {
return toUserName;
}
@XmlElement(name = "ToUserName")
@XmlJavaTypeAdapter(value = CDATAdapter.class)
public void setToUserName(String toUserName) {
this.toUserName = toUserName;
}
public String getFromUserName() {
return fromUserName;
}
@XmlElement(name = "FromUserName")
@XmlJavaTypeAdapter(value = CDATAdapter.class)
public void setFromUserName(String fromUserName) {
this.fromUserName = fromUserName;
}
public Long getCreateTime() {
return createTime;
}
@XmlElement(name = "CreateTime")
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
public String getMsgType() {
return msgType;
}
@XmlElement(name = "MsgType")
@XmlJavaTypeAdapter(value = CDATAdapter.class)
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public String getContent() {
return content;
}
@XmlElement(name = "Content")
@XmlJavaTypeAdapter(value = CDATAdapter.class)
public void setContent(String content) {
this.content = content;
}
public Integer getFuncFlag() {
return funcFlag;
}
@XmlElement(name = "FuncFlag")
public void setFuncFlag(Integer funcFlag) {
this.funcFlag = funcFlag;
}
}
package com.spacetech.common.utils.baidu;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONObject;
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import com.baidubce.services.bos.model.BosObject;
import com.baidubce.services.bos.model.ObjectMetadata;
import com.spacetech.common.exception.ApiException;
import com.spacetech.common.exception.FilePutErrorException;
import com.spacetech.common.utils.DateUtil;
import com.spacetech.common.utils.FfmpegUtil;
import com.spacetech.common.utils.FileHashUtil;
import com.spacetech.common.utils.FileUtil;
import com.spacetech.common.utils.OSSClientUtil;
import com.spacetech.common.utils.StringUtil;
@Component
@Transactional(readOnly = true)
public class BOSClientUtil {
public static final String[] audioFileTypes = new String[] { "mp3", "wav", "wma", "mid", "m4a" };
public static final String[] videoFileTypes = new String[] { "asx", "asf", "mpg", "wmv", "3gp", "mov", "avi", "flv",
"mp4" };
public static final String[] imageFileTypes = new String[] { "jpg", "gif", "png", "webp", "bmp", "tiff" };
public static final String[] OSSimageFileTypes = new String[] { "jpg", "webp", "png", "bmp" };
public static final String[] OSSOfficeFileTypes = new String[] { "doc", "docx", "wps", "pdf", "xls", "xlsx", "pptx",
"ppt" };
public static String ALI_AK = "8baae78620a94024b9042d763a99b3d7";
public static String ALI_SK = "75623a1b96824965a7caaff5edb290d3";
public static final String BUCKET_NAME = "weixt-static";
public static final String SQXY_BUCKET_NAME = "weixt-sqxy";
public static final String OFFICE_BUCKET_NAME = "weixt-office";
public static final String BUCKET_NAME_EXPORT = "weixt-export";
public static final String ALI_IMAGE_URL_HTPPS = "https://bstatic.weixiaotong.com.cn/";
public static final String ALI_OFFICE_URL_HTPPS = "https://weixtoffice.weixiaotong.com.cn/";
public static final String ALI_OFFICEBUCKET_URL = "https://weixtoffice.weixiaotong.com.cn";
private static Logger logger = LoggerFactory.getLogger(BOSClientUtil.class);
private static BosClient bosClient =null;
private static BosClient getBOSClient() {
// 初始化一个BosClient
if(bosClient==null){
BosClientConfiguration config = new BosClientConfiguration();
config.setCredentials(new DefaultBceCredentials(ALI_AK, ALI_SK));
bosClient=new BosClient(config);
}
return bosClient;
}
private static String getCndUrl(String bucketName){
if (StringUtil.isNullOrEmpty(bucketName)) {
logger.warn("BOS bucketName未配置有误");
return "";
}
if(BUCKET_NAME.equals(bucketName)){
return ALI_IMAGE_URL_HTPPS;
}else if (OFFICE_BUCKET_NAME.equals(bucketName)) {
return ALI_OFFICEBUCKET_URL;
}else{
logger.warn("BOS bucketName配置有误bucketName=" + bucketName);
throw new ApiException("BOS bucketName错误:"+bucketName);
}
}
public static void initOSSClientParam(String ali_ak, String ali_sk) {
if (StringUtil.isNotEmpty(ali_ak)) {
ALI_AK = ali_ak;
ALI_SK = ali_sk;
} else {
logger.warn("BOS配置有误ali_ak=" + ali_ak + " ali_sk=" + ali_sk);
}
}
/**
* 通过文件名读取文件,并提交到阿里OSS上,上传文件后将原始文件删除。
* @param filename
* @param compressFlag
* @return
* @throws Exception
*/
public static String putFile(String filename,String bucketName) throws Exception {
logger.info("put qiniu filename=" + filename+" bucketName="+bucketName);
String filetype = getDefaultFileType(filename);
String newFileName = "";
String filekey = getFileSha1Key(filename, filetype);
if (isVideo(filetype)) {
newFileName = FfmpegUtil.encodeToMp4Video(filename, filekey);
} else {
newFileName = filename;
}
String result = getCndUrl(bucketName) + putOSSFile(newFileName, bucketName);
if (StringUtil.isNotEmpty(result)) {
return result;
} else {
logger.error("图片上传错误" + result + " filename=" + filename+" bucketName="+bucketName);
throw new FilePutErrorException("result:" + result);
}
}
/**
* 不上传文件,仅仅获取截屏和时间
* @param filename
* @param startTime
* @param bucketName
* @return
* time 视频时长
* picUrl 视频封面
* url 文件路径
* @throws Exception
*/
public static JSONObject processFileToCloud(String filename, String startTime,
String bucketName) throws Exception {
if(StringUtil.isNullOrEmpty(filename)){
logger.error("文件不存bucketName="+bucketName);
throw new ApiException("文件不存在");
}
String filetype = FileUtil.getFileType(filename);
String filekey = getFileSha1Key(filename, filetype);
JSONObject result = new JSONObject();
if (isVideo(filetype)) {
result.put("time", FfmpegUtil.getVideoTime(filename));
result.put("picUrl", getVideoThumbnail(filename, startTime, bucketName, filekey));
}
result.put("url", putFile(filename, bucketName));
if (!result.isEmpty()) {
return result;
} else {
throw new FilePutErrorException("转码失败!");
}
}
private final static String VIDEO_THUMBNAIL_STARTTIME = "00:00:03";
public static JSONObject processFileToCloud(String filename,
String bucketName) {
try{
return processFileToCloud(filename, VIDEO_THUMBNAIL_STARTTIME, bucketName);
}catch(Exception e){
logger.error("processFileToCloud错误,filename="+filename+" bucketName="+bucketName,e);
throw new ApiException(e.getMessage());
}
}
/**
* 推入默认BUCKET
* @param filename
* @return
* * time 视频时长
* picUrl 视频封面
* url 文件路径
* @throws Exception
*/
public static JSONObject putFileToStaticBucketCloud(String filename) {
try{
return processFileToCloud(filename, BUCKET_NAME);
}catch(Exception e){
throw new ApiException(e.getMessage());
}
}
/**
* 推入默认BUCKET
* @param filename
* @param bucketName
* @return
* @throws Exception
*/
public static String putImgToStaticBucketCloud(String filename) {
try{
return processFileToCloud(filename, BUCKET_NAME).getString("url");
}catch(Exception e){
throw new ApiException(e.getMessage());
}
}
private static String getFileSha1Key(String filename, String filetype) throws Exception {
return FileHashUtil.getSHA1Checksum(filename) + System.currentTimeMillis() + "." + filetype;
}
/**
* 获取截屏,并上传到CDN,返回文件路径
*
* @param filename
* @param startTime
* @param cdnUrl
* @param bucketName
* @param filekey
* @return
* @throws InterruptedException
* @throws Exception
*/
private static String getVideoThumbnail(String filename, String startTime, String bucketName,
String filekey) throws InterruptedException, Exception {
String picUrl = "";
String makeImgbyvideoFilename = FfmpegUtil.makeImgbyvideo(filename, filekey, "", startTime);
if (StringUtil.isNullOrEmpty(makeImgbyvideoFilename)) {
logger.error("获取缩略图失败:" + makeImgbyvideoFilename + " filename="+filename);
return picUrl;
}
File imagefile = new File(makeImgbyvideoFilename);
if (!imagefile.exists()) {
Thread.sleep(500);
}
if (imagefile.exists()) {
return getCndUrl(bucketName) + putOSSFile(makeImgbyvideoFilename, bucketName);
}
logger.error("获取缩略图失败:" + makeImgbyvideoFilename + " filename="+filename);
return picUrl;
}
/**
* 判断是否属于视频阿里OSS图片处理支持的格式
*
* @param fileType
* @return
*/
public static boolean getFileTypeIsOSSImageSupport(String fileType) {
return Arrays.<String>asList(OSSimageFileTypes).contains(fileType);
}
/**
* 判断是否office文档
*
* @param fileType
* @return
*/
public static boolean isFileTypeIsOSSOffice(String fileType) {
return Arrays.<String>asList(OSSOfficeFileTypes).contains(fileType);
}
private static void cleanFiles(String filekey) {
FileUtil.delDiskFile(FfmpegUtil.TEMPPATH, filekey + ".HD.flv");
FileUtil.delDiskFile(FfmpegUtil.TEMPPATH, filekey + ".HD.mp4");
FileUtil.delDiskFile(FfmpegUtil.TEMPPATH, filekey + ".bmp");
}
/**
* 判断是否属于视频mp3
*
* @param fileType
* @return
*/
public static boolean isVideo(String fileType) {
boolean isVideo = Arrays.<String>asList(videoFileTypes).contains(fileType);
return isVideo;
}
public static String putOSSFile(String filename, String bucketName) throws Exception {
String filetype = getDefaultFileType(filename);
String filekey = FileHashUtil.getSHA1Checksum(filename) + "." + filetype;
BosClient client = getBOSClient();
Object object = getBosObjectInfo(client, filekey, bucketName);
if (object != null) {
logger.info("oss file exists:" + filekey + " filename=" + filename);
client.shutdown();
return filekey;
}
// 初始化OSSClient
try {
// 获取指定文件的输入流
File file = new File(filename);
// 创建上传Object的Metadata
ObjectMetadata meta = new ObjectMetadata();
// 必须设置ContentLength
long filelength = file.length();
meta.setContentLength(filelength);
client.putObject(bucketName, filekey, file,meta);
// 上传以后删除文件
file.delete();
logger.info("SAFE-BOS文件上传成功,远程文件名:" + filekey + " 本地文件名:" + filename + " 文件大小:"
+ filelength / 1024 + "k");
System.out.println("SAFE-BOS文件上传成功,远程文件名:" + filekey + " 本地文件名:" + filename + " 文件大小:"
+ filelength / 1024 + "k,开始时间"+DateUtil.getCurrentAllTime());
return filekey;
} catch (Exception e) {
logger.error("文件上传失败,错误原因:filename=" + filename, e);
throw new RuntimeException("文件上传失败,错误原因:" + e.getMessage());
} finally {
client.shutdown();
}
}
public static String getDefaultFileType(String filename) {
String filetype = getFileType(filename);
if (filetype != null) {
filetype = filetype.toLowerCase();
if (filetype.equals("jpeg")) {
filetype = "jpg";
}
}
return filetype;
}
/**
* 获取文件类型 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
*
* @param fileName
* @return
*/
public static String getFileType(String fileName) {
// 获取上传文件类型的扩展名,先得到.的位置,再截取从.的下一个位置到文件的最后,最后得到扩展名
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
/**
* 通过文件的HASH值获取阿里OSS文件信息
*
* @return
* @return
* @throws Exception
*/
public static BosObject getBosObjectInfo(BosClient client, String key, String bucketName) throws IOException {
// 初始化OSSClient
BosObject result = null;
try {
// 获取Object,返回结果为OSSObject对象
result = client.getObject(bucketName, key);
} catch (Exception e) {
}
return result;
}
public static void main(String[] args) {
String filename="/Users/hbz/work/share/180125163276513550.jpg";
for(int i=0;i<100;i++){
System.out.println("开始:"+DateUtil.getCurrentAllTime());
putFileToStaticBucketCloud(filename);
}
//getBOSClient();
try {
//OSSClientUtil.putOSSFile(filename, OSSClientUtil.BUCKET_NAME, false);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.spacetech.common.utils.baidu;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.spacetech.common.utils.NacosUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baidu.aip.face.AipFace;
import com.baidu.aip.ocr.AipOcr;
import com.spacetech.common.utils.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 人脸图片质量检测api,所有上传的人脸照片都需要先经过该api检测。
*
* @author yejianfei
*
*/
public class FaceDetectUtil {
private static Logger logger = LoggerFactory.getLogger(FaceDetectUtil.class);
private static final String OCR_AK = "";
private static final String OCR_SK = "";
private static final String DETECT_AK = "";
private static final String DETECT_SK = "";
public static Integer DETECT_SUCCESS = 1;
public static Integer DETECT_FAIL = -1;
private static AipFace faceClient = null;
private static AipOcr ocrClient = null;
public static AipOcr getOcrClient() {
if (ocrClient == null) {
// String ocrAk = zkUtil.getData(ConfigUpdater.PATH + "/baidu_ocr_ak");
String ocrAk = NacosUtil.getConfig("baidu_ocr_ak");
String ocrSk = NacosUtil.getConfig("baidu_ocr_sk");
ocrClient = new AipOcr("17747517", ocrAk, ocrSk);
// 可选:设置网络连接参数
ocrClient.setConnectionTimeoutInMillis(2000);
ocrClient.setSocketTimeoutInMillis(60000);
}
return ocrClient;
}
public static AipFace getFaceClient() {
if (faceClient == null) {
String detectAk = NacosUtil.getConfig("baidu_detect_ak");
String detectSk = NacosUtil.getConfig("baidu_detect_sk");
faceClient = new AipFace("17870683", detectAk, detectSk);
// 可选:设置网络连接参数
faceClient.setConnectionTimeoutInMillis(2000);
faceClient.setSocketTimeoutInMillis(60000);
}
return faceClient;
}
public static void main(String[] args) {
System.out.println(detectFace("https://pic.qqtn.com/up/2018-5/15253967211555188.jpg"));
}
public static JSONObject detectFace(String fileUrl) {
if (fileUrl == null || fileUrl.isEmpty()) {
return makeFailResult("照片不存在");
}
HashMap<String, String> options = new HashMap<String, String>();
options.put("face_field", "quality");
options.put("max_face_num", "1");
options.put("face_type", "LIVE");
options.put("liveness_control", "NONE");
String image = fileUrl;
String imageType = "URL";
JSONObject result = getFaceClient().detect(image, imageType, options);
logger.info("detectFace fileUrl=" + fileUrl + " result=" + result.toString());
int errorCode = 0;
try {
errorCode = StringUtil.getIntOfObj(result.getInt("error_code"));
} catch (Exception e) {
logger.error("detectFace人脸返回的错误编码无法转为int; fileUrl=" + fileUrl + " errorCode="
+ result.getString("error_code") +" 失败原因=" + e.getMessage(), e);
return makeFailResult("人脸检测超时,请重试!");
}
if (errorCode > 0) {
return makeFailResult("未检测到人脸");
}
JSONObject resultJson = result.getJSONObject("result");
JSONArray faceList = resultJson.getJSONArray("face_list");
JSONObject faceJson = faceList.getJSONObject(0);
if (checkAngle(faceJson)) {
return makeFailResult("人脸倾斜角度过大");
}
if (checkSize(faceJson)) {
return makeFailResult("人脸尺寸过小");
}
if (checkQuality(faceJson)) {
return makeFailResult("人脸有遮挡");
}
if (checkIllumination(faceJson)) {
return makeFailResult("光照太弱");
}
if (checkBlur(faceJson)) {
return makeFailResult("照片太模糊");
}
return makeSuccessResult();
}
/**
* 检测角度
*
* @return
*/
private static boolean checkAngle(JSONObject faceJson) {
JSONObject angleJson = faceJson.getJSONObject("angle");
double roll = angleJson.getDouble("roll");
double pitch = angleJson.getDouble("pitch");
double yaw = angleJson.getDouble("yaw");
// 任意一个倾斜角度大于20就不合格
return angleGreaterThan20(roll) || angleGreaterThan20(pitch) || angleGreaterThan20(yaw);
}
/**
* 检测大小
*
* @return
*/
private static boolean checkSize(JSONObject faceJson) {
JSONObject locationJson = faceJson.getJSONObject("location");
int width = locationJson.getInt("width");
int height = locationJson.getInt("height");
return sizeLessThen200(width) || sizeLessThen200(height);
}
private static boolean checkQuality(JSONObject faceJson) {
JSONObject qualityJson = faceJson.getJSONObject("quality");
JSONObject occlusionJson = qualityJson.getJSONObject("occlusion");
return isOcclusionJsonOutOfLimit(occlusionJson, "right_eye", 0.4)
|| isOcclusionJsonOutOfLimit(occlusionJson, "left_eye", 0.4)
|| isOcclusionJsonOutOfLimit(occlusionJson, "right_cheek", 0.4)
|| isOcclusionJsonOutOfLimit(occlusionJson, "left_cheek", 0.4)
|| isOcclusionJsonOutOfLimit(occlusionJson, "nose", 0.4)
|| isOcclusionJsonOutOfLimit(occlusionJson, "mouth", 0.4)
|| isOcclusionJsonOutOfLimit(occlusionJson, "chin_contour", 0.4);
// 任意一个倾斜角度大于20就不合格
}
private static boolean isOcclusionJsonOutOfLimit(JSONObject occlusionJson, String type, Double limit) {
return occlusionJson.getDouble(type) > limit;
}
private static boolean checkBlur(JSONObject faceJson) {
JSONObject qualityJson = faceJson.getJSONObject("quality");
return qualityJson.getDouble("blur") > 0.5;
}
private static boolean checkIllumination(JSONObject faceJson) {
JSONObject qualityJson = faceJson.getJSONObject("quality");
int illumination = qualityJson.getInt("illumination");
return illumination < 100;
}
private static boolean sizeLessThen200(int size) {
return size < 200;
}
private static boolean angleGreaterThan20(double angle) {
return Math.abs(angle) > 20;
}
private static JSONObject makeFailResult(String errorMsg) {
JSONObject json = new JSONObject();
json.put("result", DETECT_FAIL);
json.put("msg", errorMsg);
return json;
}
private static JSONObject makeSuccessResult() {
JSONObject json = new JSONObject();
json.put("msg", "SUCCESS");
json.put("result", DETECT_SUCCESS);
return json;
}
}
package com.spacetech.common.utils.cache;
import java.io.IOException;
import com.spacetech.common.utils.NacosUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.spacetech.common.ConstantVar;
import com.spacetech.common.utils.StringUtil;
import net.rubyeye.xmemcached.utils.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.PlainCallbackHandler;
import org.springframework.stereotype.Component;
@Component
public class MemCacheCommon {
private static Logger logger = LoggerFactory.getLogger(MemCacheCommon.class);
public static MemcachedClient initMemCache(String ip,String username,String password) {
String memcacheutilIp = NacosUtil.getConfig(ip);
String memcacheutilUsername = NacosUtil.getConfig(username);
String memcacheutilPassword = NacosUtil.getConfig(password);
if (StringUtil.isNullOrEmpty(memcacheutilIp) || memcacheutilIp.indexOf(":") < 0) {
throw new RuntimeException("缓存未配置或者格式有误(127.0.0.1:11211)");
}
MemcachedClient client = null;
if (StringUtil.isNotEmpty(memcacheutilUsername)
&& !ConstantVar.SPACE_PLACEHOLDER.equals(memcacheutilUsername)) {
client = start(memcacheutilIp, memcacheutilUsername, memcacheutilPassword);
} else {
client = start(memcacheutilIp);
}
logger.info("memcache start sucess zkIpAndPortPath=" + memcacheutilIp);
return client;
}
public static MemcachedClient start(String ipPort) {
try {
return new MemcachedClient(new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY).build(),
AddrUtil.getAddresses(ipPort));
} catch (IOException e) {
logger.error("获取缓存发生错误 ipPort=" + ipPort, e);
return null;
}
}
public static MemcachedClient start(String ipPort, String username, String password) {
AuthDescriptor ad = new AuthDescriptor(new String[] { "PLAIN" }, new PlainCallbackHandler(username, password));
try {
return new MemcachedClient(
new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY).setAuthDescriptor(ad).build(),
AddrUtil.getAddresses(ipPort));
} catch (IOException e) {
logger.error("获取缓存发生错误 ipPort=" + ipPort, e);
return null;
}
}
public static void set(MemcachedClient client, String key, Object obj) {
try {
client.set(key, 0, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("设置数据发现异常:" + e.getMessage());
}
}
public static void delete(MemcachedClient client, String key) {
try {
client.delete(key);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("删除数据发现异常:" + e.getMessage());
}
}
public static void set(MemcachedClient client, String key, int expire, Object obj) {
try {
client.set(key, expire, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("设置数据发现异常:" + e.getMessage());
}
}
public static Object get(MemcachedClient client, String key) {
try {
return client.get(key);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("获取数据发现异常:" + e.getMessage());
}
}
public static String getMemcacheKey(String type, String keyid) {
return type + "_" + keyid;
}
}
package com.spacetech.common.utils.cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.spy.memcached.MemcachedClient;
public class MemCacheCommonUtil extends MemCacheCommon {
private static Logger logger = LoggerFactory.getLogger(MemCacheCommonUtil.class);
private static MemcachedClient client = null;
public static void initMemCache() {
client = initMemCache("memcacheutil_ip", "memcacheutil_username", "memcacheutil_password");
MemCacheForOnecardCommonUtil.initMemCache();
}
public static void set(String key, Object obj) {
try {
set(client, key, 0, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("设置数据发现异常:" + e.getMessage());
}
}
public static void delete(String key) {
try {
delete(client, key);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("删除数据发现异常:" + e.getMessage());
}
}
public static void set(String key, int expire, Object obj) {
try {
set(client, key, expire, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("设置数据发现异常:" + e.getMessage());
}
}
public static Object get(String key) {
try {
return get(client, key);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("获取数据发现异常:" + e.getMessage());
}
}
}
package com.spacetech.common.utils.cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.spy.memcached.MemcachedClient;
public class MemCacheForOnecardCommonUtil extends MemCacheCommon {
private static Logger logger = LoggerFactory.getLogger(MemCacheForOnecardCommonUtil.class);
private static MemcachedClient client = null;
public static void initMemCache() {
client = initMemCache("memcacheforonecardutil_ip", "memcacheforonecardutil_username",
"memcacheforonecardutil_password");
}
public static void set(String key, Object obj) {
try {
set(client, key, 0, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("设置数据发现异常:" + e.getMessage());
}
}
public static void delete(String key) {
try {
delete(client, key);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("删除数据发现异常:" + e.getMessage());
}
}
public static void set(String key, int expire, Object obj) {
try {
set(client, key, expire, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("设置数据发现异常:" + e.getMessage());
}
}
public static Object get(String key) {
try {
return get(client, key);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("获取数据发现异常:" + e.getMessage());
}
}
}
package com.spacetech.common.utils.cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.spy.memcached.MemcachedClient;
public class MemCacheSafeCommonUtil extends MemCacheCommon {
private static Logger logger = LoggerFactory.getLogger(MemCacheSafeCommonUtil.class);
private static MemcachedClient client = null;
public static void initMemCache() {
client = initMemCache("memcachesafeutil_ip", "memcachesafeutil_username", "memcachesafeutil_password");
}
public static void set(String key, Object obj) {
try {
set(client, key, 0, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("设置数据发现异常:" + e.getMessage());
}
}
public static void delete(String key) {
try {
delete(client, key);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("删除数据发现异常:" + e.getMessage());
}
}
public static void set(String key, int expire, Object obj) {
try {
set(client, key, expire, obj);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("设置数据发现异常:" + e.getMessage());
}
}
public static Object get(String key) {
try {
return get(client, key);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("获取缓存发生错误", e);
throw new RuntimeException("获取数据发现异常:" + e.getMessage());
}
}
}
package com.spacetech.common.utils.wechat;
@SuppressWarnings("serial")
public class AesException extends Exception {
public final static int OK = 0;
public final static int ValidateSignatureError = -40001;
public final static int ParseXmlError = -40002;
public final static int ComputeSignatureError = -40003;
public final static int IllegalAesKey = -40004;
public final static int ValidateAppidError = -40005;
public final static int EncryptAESError = -40006;
public final static int DecryptAESError = -40007;
public final static int IllegalBuffer = -40008;
//public final static int EncodeBase64Error = -40009;
//public final static int DecodeBase64Error = -40010;
//public final static int GenReturnXmlError = -40011;
private int code;
private static String getMessage(int code) {
switch (code) {
case ValidateSignatureError:
return "签名验证错误";
case ParseXmlError:
return "xml解析失败";
case ComputeSignatureError:
return "sha加密生成签名失败";
case IllegalAesKey:
return "SymmetricKey非法";
case ValidateAppidError:
return "appid校验失败";
case EncryptAESError:
return "aes加密失败";
case DecryptAESError:
return "aes解密失败";
case IllegalBuffer:
return "解密后得到的buffer非法";
// case EncodeBase64Error:
// return "base64加密错误";
// case DecodeBase64Error:
// return "base64解密错误";
// case GenReturnXmlError:
// return "xml生成失败";
default:
return null; // cannot be
}
}
public int getCode() {
return code;
}
AesException(int code) {
super(getMessage(code));
this.code = code;
}
}
package com.spacetech.common.utils.wechat;
import java.util.ArrayList;
class ByteGroup {
ArrayList<Byte> byteContainer = new ArrayList<Byte>();
public byte[] toBytes() {
byte[] bytes = new byte[byteContainer.size()];
for (int i = 0; i < byteContainer.size(); i++) {
bytes[i] = byteContainer.get(i);
}
return bytes;
}
public ByteGroup addBytes(byte[] bytes) {
for (byte b : bytes) {
byteContainer.add(b);
}
return this;
}
public int size() {
return byteContainer.size();
}
}
package com.spacetech.common.utils.wechat;
public class EmojiFilter {
private static boolean isEmojiCharacter(char codePoint) {
return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
|| (codePoint == 0xD)
|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
|| ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
|| ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
}
/**
* 过滤emoji 或者 其他非文字类型的字符
*
* @param source
* @return
*/
public static String filterEmoji(String source) {
// if (!containsEmoji(source)) {
// return source;// 如果不包含,直接返回
// }
// 到这里铁定包含
StringBuilder buf = null;
int len = source.length();
for (int i = 0; i < len; i++) {
char codePoint = source.charAt(i);
if (isEmojiCharacter(codePoint)) {
if (buf == null) {
buf = new StringBuilder(source.length());
}
buf.append(codePoint);
} else {
}
}
if (buf == null) {
return source;// 如果没有找到 emoji表情,则返回源字符串
} else {
if (buf.length() == len) {// 这里的意义在于尽可能少的toString,因为会重新生成字符串
buf = null;
return source;
} else {
return buf.toString();
}
}
}
}
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
package com.spacetech.common.utils.wechat;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* 提供基于PKCS7算法的加解密接口.
*/
public class PKCS7Encoder {
static Charset CHARSET = Charset.forName("utf-8");
static int BLOCK_SIZE = 32;
/**
* 获得对明文进行补位填充的字节.
*
* @param count 需要进行填充补位操作的明文字节个数
* @return 补齐用的字节数组
*/
public static byte[] encode(int count) {
// 计算需要填充的位数
int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
if (amountToPad == 0) {
amountToPad = BLOCK_SIZE;
}
// 获得补位所用的字符
char padChr = chr(amountToPad);
String tmp = new String();
for (int index = 0; index < amountToPad; index++) {
tmp += padChr;
}
return tmp.getBytes(CHARSET);
}
/**
* 删除解密后明文的补位字符
*
* @param decrypted
* 解密后的明文
* @return 删除补位字符后的明文
*/
public static byte[] decode(byte[] decrypted) {
int pad = (int) decrypted[decrypted.length - 1];
if (pad < 1 || pad > 32) {
pad = 0;
}
return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
}
/**
* 将数字转化成ASCII码对应的字符,用于对明文进行补码
*
* @param a
* 需要转化的数字
* @return 转化得到的字符
*/
public static char chr(int a) {
byte target = (byte) (a & 0xFF);
return (char) target;
}
}
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
package com.spacetech.common.utils.wechat;
import java.security.MessageDigest;
import java.util.Arrays;
/**
* SHA1 class
*
* 计算公众平台的消息签名接口.
*/
class SHA1 {
/**
* 用SHA1算法生成安全签名
* @param token 票据
* @param timestamp 时间戳
* @param nonce 随机字符串
* @param encrypt 密文
* @return 安全签名
* @throws AesException
*/
public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException
{
try {
String[] array = new String[] { token, timestamp, nonce, encrypt };
StringBuffer sb = new StringBuffer();
// 字符串排序
Arrays.sort(array);
for (int i = 0; i < 4; i++) {
sb.append(array[i]);
}
String str = sb.toString();
// SHA1签名生成
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(str.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
return hexstr.toString();
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.ComputeSignatureError);
}
}
}
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
/**
* 针对org.apache.commons.codec.binary.Base64,
* 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本)
* 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi
*/
package com.spacetech.common.utils.wechat;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
/**
* 提供接收和推送给公众平台消息的加解密接口(UTF8编码的字符串).
* <ol>
* <li>第三方回复加密消息给公众平台</li>
* <li>第三方收到公众平台发送的消息,验证消息的安全性,并对消息进行解密。</li>
* </ol>
* 说明:异常java.security.InvalidKeyException:illegal Key Size的解决方案
* <ol>
* <li>在官方网站下载JCE无限制权限策略文件(JDK7的下载地址:
* http://www.oracle.com/technetwork/java/javase
* /downloads/jce-7-download-432124.html</li>
* <li>下载后解压,可以看到local_policy.jar和US_export_policy.jar以及readme.txt</li>
* <li>如果安装了JRE,将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件</li>
* <li>如果安装了JDK,将两个jar文件放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件</li>
* </ol>
*/
public class WXBizMsgCrypt {
private static Logger logger = LoggerFactory.getLogger(WXBizMsgCrypt.class);
static Charset CHARSET = Charset.forName("utf-8");
Base64 base64 = new Base64();
byte[] aesKey;
String token;
String appId;
/**
* 构造函数
*
* @param token
* 公众平台上,开发者设置的token
* @param encodingAesKey
* 公众平台上,开发者设置的EncodingAESKey
* @param appId
* 公众平台appid
*
* @throws AesException
* 执行失败,请查看该异常的错误码和具体的错误信息
*/
public WXBizMsgCrypt(String token, String encodingAesKey, String appId) throws AesException {
if (encodingAesKey.length() != 43) {
throw new AesException(AesException.IllegalAesKey);
}
this.token = token;
this.appId = appId;
aesKey = Base64.decodeBase64((encodingAesKey + "=").getBytes());
}
public WXBizMsgCrypt(String token, String encodingAesKey) throws AesException {
if (encodingAesKey.length() != 43) {
throw new AesException(AesException.IllegalAesKey);
}
this.token = token;
aesKey = Base64.decodeBase64((encodingAesKey + "=").getBytes());
}
// 生成4个字节的网络字节序
byte[] getNetworkBytesOrder(int sourceNumber) {
byte[] orderBytes = new byte[4];
orderBytes[3] = (byte) (sourceNumber & 0xFF);
orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF);
orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF);
orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF);
return orderBytes;
}
// 还原4个字节的网络字节序
int recoverNetworkBytesOrder(byte[] orderBytes) {
int sourceNumber = 0;
for (int i = 0; i < 4; i++) {
sourceNumber <<= 8;
sourceNumber |= orderBytes[i] & 0xff;
}
return sourceNumber;
}
// 随机生成16位字符串
String getRandomStr() {
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 16; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* 对明文进行加密.
*
* @param text
* 需要加密的明文
* @return 加密后base64编码的字符串
* @throws AesException
* aes加密失败
*/
String encrypt(String randomStr, String text) throws AesException {
ByteGroup byteCollector = new ByteGroup();
byte[] randomStrBytes = randomStr.getBytes(CHARSET);
byte[] textBytes = text.getBytes(CHARSET);
byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);
byte[] appidBytes = appId.getBytes(CHARSET);
// randomStr + networkBytesOrder + text + appid
byteCollector.addBytes(randomStrBytes);
byteCollector.addBytes(networkBytesOrder);
byteCollector.addBytes(textBytes);
byteCollector.addBytes(appidBytes);
// ... + pad: 使用自定义的填充方式对明文进行补位填充
byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());
byteCollector.addBytes(padBytes);
// 获得最终的字节流, 未加密
byte[] unencrypted = byteCollector.toBytes();
try {
// 设置加密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
// 加密
byte[] encrypted = cipher.doFinal(unencrypted);
// 使用BASE64对加密后的字符串进行编码
String base64Encrypted = new String(base64.encode(encrypted));
return base64Encrypted;
} catch (Exception e) {
logger.error("aes加密失败" + AesException.EncryptAESError + ",错误原因:" + e.getMessage(), e);
throw new AesException(AesException.EncryptAESError);
}
}
/**
* 对密文进行解密.
*
* @param text
* 需要解密的密文
* @return 解密得到的明文
* @throws AesException
* aes解密失败
*/
public JSONObject decrypt(String text) throws AesException {
byte[] original;
try {
// 设置解密模式为AES的CBC模式
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);
// 使用BASE64对密文进行解码
byte[] encrypted = Base64.decodeBase64(text.getBytes());
// 解密
original = cipher.doFinal(encrypted);
} catch (Exception e) {
logger.error("aes解密失败" + AesException.DecryptAESError + ",错误原因:" + e.getMessage(), e);
throw new AesException(AesException.DecryptAESError);
}
JSONObject result = new JSONObject();
String xmlContent, from_appid;
try {
// 去除补位字符
byte[] bytes = PKCS7Encoder.decode(original);
// 分离16位随机字符串,网络字节序和AppId
byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);
int xmlLength = recoverNetworkBytesOrder(networkOrder);
result.put("xmlLength", xmlLength);
xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
result.put("xmlContent", xmlContent);
from_appid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), CHARSET);
result.put("from_appid", from_appid);
} catch (Exception e) {
logger.error("aes解密失败" + AesException.IllegalBuffer + ",错误原因:" + e.getMessage(), e);
throw new AesException(AesException.IllegalBuffer);
}
// appid不相同的情况
// if (!from_appid.equals(appId)) {
// throw new AesException(AesException.ValidateAppidError);
// }
return result;
}
/**
* 将公众平台回复用户的消息加密打包.
* <ol>
* <li>对要发送的消息进行AES-CBC加密</li>
* <li>生成安全签名</li>
* <li>将消息密文和安全签名打包成xml格式</li>
* </ol>
*
* @param replyMsg
* 公众平台待回复用户的消息,xml格式的字符串
* @param timeStamp
* 时间戳,可以自己生成,也可以用URL参数的timestamp
* @param nonce
* 随机串,可以自己生成,也可以用URL参数的nonce
*
* @return 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串
* @throws AesException
* 执行失败,请查看该异常的错误码和具体的错误信息
*/
public String encryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException {
// 加密
String encrypt = encrypt(getRandomStr(), replyMsg);
// 生成安全签名
if (timeStamp == "") {
timeStamp = Long.toString(System.currentTimeMillis());
}
String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt);
// System.out.println("发送给平台的签名是: " + signature[1].toString());
// 生成发送的xml
String result = XMLParse.generate(encrypt, signature, timeStamp, nonce);
return result;
}
/**
* 检验消息的真实性,并且获取解密后的明文.
* <ol>
* <li>利用收到的密文生成安全签名,进行签名验证</li>
* <li>若验证通过,则提取xml中的加密消息</li>
* <li>对消息进行解密</li>
* </ol>
*
* @param msgSignature
* 签名串,对应URL参数的msg_signature
* @param timeStamp
* 时间戳,对应URL参数的timestamp
* @param nonce
* 随机串,对应URL参数的nonce
* @param postData
* 密文,对应POST请求的数据
*
* @return 解密后的原文
* @throws AesException
* 执行失败,请查看该异常的错误码和具体的错误信息
*/
public String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData) throws AesException {
// 密钥,公众账号的app secret
// 提取密文
Object[] encrypt = XMLParse.extract(postData);
// 验证安全签名
String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt[1].toString());
// 和URL中的签名比较是否相等
// System.out.println("第三方收到URL中的签名:" + msg_sign);
// System.out.println("第三方校验签名:" + signature);
if (!signature.equals(msgSignature)) {
throw new AesException(AesException.ValidateSignatureError);
}
// 解密
String result = decrypt(encrypt[1].toString()).getString("xmlContent");
return result;
}
/**
* 验证URL
*
* @param msgSignature
* 签名串,对应URL参数的msg_signature
* @param timeStamp
* 时间戳,对应URL参数的timestamp
* @param nonce
* 随机串,对应URL参数的nonce
* @param echoStr
* 随机串,对应URL参数的echostr
*
* @return 解密之后的echostr
* @throws AesException
* 执行失败,请查看该异常的错误码和具体的错误信息
*/
public String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr) throws AesException {
String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr);
if (!signature.equals(msgSignature)) {
throw new AesException(AesException.ValidateSignatureError);
}
String result = decrypt(echoStr).getString("xmlContent");
return result;
}
}
\ No newline at end of file
package com.spacetech.common.utils.wechat;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Transient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spacetech.common.ConstantVar;
import com.spacetech.common.exception.ApiException;
import com.spacetech.common.utils.AESUtil;
import com.spacetech.common.utils.DateUtil;
import com.spacetech.common.utils.HttpClientUtil;
import com.spacetech.common.utils.StringUtil;
public class WechatApiUtil {
private static Logger logger = LoggerFactory.getLogger(WechatApiUtil.class);
public static void main(String[] args) {
}
public static final String SYNC_METHOD_SAVE = "save";
public static final String SYNC_METHOD_UPDATE = "update";
public static final String SYNC_METHOD_DELETE = "delete";
/**
* 资质认证成功(此时立即获得接口权限)
*/
public static final String QUALIFICATION_VERIFY_SUCCESS = "qualification_verify_success";
/**
* 资质认证失败
*/
public static final String QUALIFICATION_VERIFY_FAIL = "qualification_verify_fail";
/**
* 名称认证成功(即命名成功)
*/
public static final String NAMING_VERIFY_SUCCESS = "naming_verify_success";
/**
* 名称认证失败(这时虽然客户端不打勾,但仍有接口权限)
*/
public static final String NAMING_VERIFY_FAIL = "naming_verify_fail";
/**
* 年审通知
*/
public static final String ANNUAL_RENEW = "annual_renew";
/**
* 认证过期失效通知
*/
public static final String VERIFY_EXPIRED = "verify_expired";
public static final String MSG_TYPE_IMAGE = "image";
public static final String MSG_TYPE_VOICE = "voice";
public static final String MSG_TYPE_LOCATION = "LOCATION";
public static final String MSG_TYPE_SHORTVIDEO = "shortvideo";// 小视频
public static final String MSG_TYPE_VIDEO = "video";
/**
* 微信加密方式
*/
public static final String WECHAT_ENCRYPT_TYPE = "aes";
public static final String EVENT_SENDMGS = "TEMPLATESENDJOBFINISH";
public static final String newsMsg = "<xml>" + "<ToUserName><![CDATA[%1$s]]></ToUserName>"
+ "<FromUserName><![CDATA[%2$s]]></FromUserName>" + "<CreateTime>%3$s</CreateTime>"
+ "<MsgType><![CDATA[news]]></MsgType>" + "<ArticleCount>%4$s</ArticleCount>" + "<Articles>%5$s</Articles>"
+ "<FuncFlag>1</FuncFlag>" + "</xml>";
public static final String newsMsgItem = "<item>" + "<Title><![CDATA[%1$s]]></Title>"
+ "<Description><![CDATA[%2$s]]></Description>" + "<PicUrl><![CDATA[%3$s]]></PicUrl>"
+ "<Url><![CDATA[%4$s]]></Url>" + "</item>";
public static final String textMsg = "<xml>" + "<ToUserName><![CDATA[%1$s]]></ToUserName>"
+ "<FromUserName><![CDATA[%2$s]]></FromUserName>" + "<CreateTime>%3$s</CreateTime>"
+ "<MsgType><![CDATA[text]]></MsgType>" + "<Content><![CDATA[%4$s]]></Content>" + "<FuncFlag>0</FuncFlag>"
+ "</xml>";
public static String assembleReplyNewsMsgItem(String title, String description, String picUrl, String url) {
String textTpl = newsMsgItem;
return textTpl.format(textTpl, title, description, picUrl, url);
}
/**
* 生成微信图文消息回复
*
* @param toUserName
* @param fromUserName
* @param list
* @return
*/
public static String assembleReplyNewsMsgList(String toUserName, String fromUserName, List<JSONObject> list) {
StringBuffer replyMsgItem = new StringBuffer();
for (JSONObject param : list) {
replyMsgItem.append(assembleReplyNewsMsgItem(param.getString("title"), param.getString("description"),
param.getString("picUrl"), param.getString("url")));
}
String textTpl = newsMsg;
return textTpl.format(textTpl, fromUserName, toUserName, DateUtil.getCurrentTime(), list.size(),
replyMsgItem.toString());
}
/**
* 生成微信普通文本回复
*
* @param toUserName
* @param fromUserName
* @param content
* @return
*/
public static String assembleReplyTextMsg(String toUserName, String fromUserName, String content) {
String textTpl = textMsg;
return textTpl.format(textTpl, fromUserName, toUserName, DateUtil.getCurrentTime(), content);
}
/**
* 微信开发者模式校验
*
* @param signature
* @param timestamp
* @param nonce
* @param token
* @return
*/
public static boolean checkSignature(String signature, String timestamp, String nonce, String token) {
String[] tmpArr = { token, timestamp, nonce };
Arrays.sort(tmpArr);
String tmpStr = ArrayToString(tmpArr);
tmpStr = SHA1Encode(tmpStr);
if (tmpStr.equalsIgnoreCase(signature)) {
return true;
} else {
return false;
}
}
/**
* 认证成功:修改认证状态和过期时间
*
* @return
*/
@Transient
public static boolean isUpdateVerifystateAndExpiredTime(String verifystate) {
return QUALIFICATION_VERIFY_SUCCESS.equals(verifystate) || NAMING_VERIFY_SUCCESS.equals(verifystate)
|| ANNUAL_RENEW.equals(verifystate) || VERIFY_EXPIRED.equals(verifystate);
}
/**
* 认证失败:修改认证状态、失败时间、失败原因
*
* @return
*/
@Transient
public static boolean isUpdateVerifystateAndFailTimeAndFailReason(String verifystate) {
return QUALIFICATION_VERIFY_FAIL.equals(verifystate) || NAMING_VERIFY_FAIL.equals(verifystate);
}
// 数组转字符串
public static String ArrayToString(String[] arr) {
StringBuffer bf = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
bf.append(arr[i]);
}
return bf.toString();
}
// sha1加密
public static String SHA1Encode(String sourceString) {
String resultString = null;
try {
resultString = new String(sourceString);
MessageDigest md = MessageDigest.getInstance("SHA-1");
resultString = byte2hexString(md.digest(resultString.getBytes()));
} catch (Exception ex) {
}
return resultString;
}
public static final String byte2hexString(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
}
return buf.toString().toUpperCase();
}
/**
* 产生相关请求参数
*
* @param paramMap
* @param appid
* @param campusid
* @return
*/
public static String createWechatOauth2State(Map<String, Object> paramMap, String appid, Long orgcode,
Long campusid) {
// 1、校验
String paramJson = "";
try {
if (paramMap == null) {
paramMap = new HashMap<String, Object>();
}
paramMap.put("orgcode", orgcode);
paramMap.put("appid", appid);
paramMap.put("campusid", StringUtil.getNullLong(campusid));
paramJson = JSON.toJSONString(paramMap);
String aesStrState = AESUtil.encrypt(paramJson, ConstantVar.AES_KEY);
return aesStrState;
} catch (Exception e) {
// e.printStackTrace();
logger.error("授权加密内容生产错误" + e.getMessage() + " 入参paramJson=" + paramJson);
return "";
}
}
/**
* 组装授权模式url和参数
*
* @param appid
* @param campusid
* @return
*/
public static String createWechatOauth2State(String appid, Long orgcode, Long campusid) {
return createWechatOauth2State(null, appid, orgcode, campusid);
}
public static String getWechatPostUrl(String postUrl, String access_token) {
if (StringUtil.isNullOrEmpty(access_token)) {
logger.error("企业微信数据同步组装token为空url=" + postUrl);
throw new ApiException("调用微信接口,access_token凭证错误");
}
String requestUrl = postUrl.replace("ACCESS_TOKEN", access_token);
return requestUrl;
}
public static final String CORP_TAG_CREATE_URL = "https://qyapi.weixin.qq.com/cgi-bin/tag/create?access_token=ACCESS_TOKEN";
public static final String CORP_TAG_UPDATE_URL = "https://qyapi.weixin.qq.com/cgi-bin/tag/update?access_token=ACCESS_TOKEN";
public static final String CORP_TAG_DELETE_URL = "https://qyapi.weixin.qq.com/cgi-bin/tag/delete?access_token=ACCESS_TOKEN&tagid=TAGID";
/**
* 企业微信通过平台角色删除标签
*
* @param roleName
* @param roleid
* @param accessToken
* @return
*/
public static JSONObject corpDeleteTag(Long roleid, String accessToken) {
String url = getWechatPostUrl(CORP_TAG_DELETE_URL, accessToken).replace("TAGID", roleid + "");
Map<String, String> resultJson = HttpClientUtil.authSubmitGetRequest(url);
logger.info("企业微信数据同步删除标签url=" + url + " roleid=" + roleid + " 返回:" + resultJson);
return JSONObject.parseObject(JSONObject.toJSONString(resultJson));
}
/**
* 企业微信通过平台角色更新标签
*
* @param roleName
* @param roleid
* @param accessToken
* @return
*/
public static JSONObject corpUpdateTag(String roleName, String roleid, String accessToken) {
JSONObject postParams = new JSONObject();
postParams.put("tagname", roleName);
postParams.put("tagid", roleid);
String url = getWechatPostUrl(CORP_TAG_UPDATE_URL, accessToken);
JSONObject resultJson = HttpClientUtil.httpPost(url, postParams);
logger.info("企业微信数据同步创建标签url=" + url + " roleid=" + roleid + " 返回:" + resultJson + " postParams="
+ JSONObject.toJSONString(postParams));
return resultJson;
}
public static JSONObject corpCreateTag(String roleName, String roleid, String accessToken) {
JSONObject postParams = new JSONObject();
postParams.put("tagname", roleName);
postParams.put("tagid", roleid);
String url = getWechatPostUrl(CORP_TAG_CREATE_URL, accessToken);
JSONObject resultJson = HttpClientUtil.httpPost(url, postParams);
logger.info("企业微信数据同步创建标签url=" + url + " roleid=" + roleid + " 返回:" + resultJson + " postParams="
+ JSONObject.toJSONString(postParams));
return resultJson;
}
public static final String CORP_ADDTAGUSERS_URL = "https://qyapi.weixin.qq.com/cgi-bin/tag/addtagusers?access_token=ACCESS_TOKEN";
/**
* 标签增加成员
*
* @param roleid
* @param userlist
* @param accessToken
* @return
*/
public static JSONObject corpAddtagusers(String roleid, List<String> userlist, String accessToken) {
JSONObject postParams = new JSONObject();
postParams.put("tagid", roleid);
postParams.put("userlist", userlist);
String url = getWechatPostUrl(CORP_ADDTAGUSERS_URL, accessToken);
JSONObject resultJson = HttpClientUtil.httpPost(url, postParams);
logger.info("企业微信数据同步创建标签成员url=" + url + " roleid=" + roleid + " 返回:" + resultJson + " postParams="
+ JSONObject.toJSONString(postParams));
return resultJson;
}
public static final String CORP_DELTAGUSERS_URL = "https://qyapi.weixin.qq.com/cgi-bin/tag/deltagusers?access_token=ACCESS_TOKEN";
/**
* 标签删除成员
*
* @param roleid
* @param userlist
* @param accessToken
* @return
*/
public static JSONObject corpDeltagusers(String roleid, List<String> userlist, String accessToken) {
JSONObject postParams = new JSONObject();
postParams.put("tagid", roleid);
postParams.put("userlist", userlist);
String url = getWechatPostUrl(CORP_DELTAGUSERS_URL, accessToken);
JSONObject resultJson = HttpClientUtil.httpPost(url, postParams);
logger.info("企业微信数据同步删除标签成员url=" + url + " roleid=" + roleid + " 返回:" + resultJson + " postParams="
+ JSONObject.toJSONString(postParams));
return resultJson;
}
public static final String CORP_SET_SCOPE_URL = "https://qyapi.weixin.qq.com/cgi-bin/agent/set_scope?access_token=ACCESS_TOKEN";
/**
* 设置授权应用可见范围
*
* @param roleid
* @param userlist
* @param accessToken
* @return
*/
public static JSONObject corpSetScope(String agentid, List<Long> roleidList, String accessToken, String corpid) {
JSONObject resultJson = new JSONObject();
if (roleidList == null || roleidList.isEmpty()) {
return resultJson;
}
if (StringUtil.isNullOrEmpty(accessToken)) {
resultJson.put("errcode", -1);
resultJson.put("errmsg", "accessToken令牌为空");
return resultJson;
}
JSONObject postParams = new JSONObject();
postParams.put("agentid", agentid);
postParams.put("allow_tag", roleidList);
String url = getWechatPostUrl(CORP_SET_SCOPE_URL, accessToken);
resultJson = HttpClientUtil.httpPost(url, postParams);
logger.info("企业微信设置授权应用可见范围corpid=" + corpid + " url=" + url + " agentid=" + agentid + " 返回:" + resultJson
+ " postParams=" + JSONObject.toJSONString(postParams));
return resultJson;
}
/**
* 获取同步返回状态码
*
* @param result
* @return
*/
public static int getCorpPostResultState(JSONObject result) {
return result == null || !getCorpPostResultIsSuccess(result) ? -1 : 1;
}
/**
* 获取同步状态是否成功 0成功
*/
public static boolean getCorpPostResultIsSuccess(JSONObject result) {
return result == null || result.getIntValue("errcode") != 0 ? false : true;
}
// 企业微信通讯录应用模块
public final static String CODE_USER_BOOK = "USER_BOOK";
public final static String CODE_MESSAGE_CENTER = "MESSAGE_CENTER";
public final static String CORP_CODE_PORTAL = "PORTAL";
public final static String CORP_CODE_HOMEWORK = "HOMEWORK";
public final static String CORP_CODE_OA = "OA";
public final static String CORP_CODE_STUSCORE = "STUSCORE";
public final static String CORP_CODE_ARCHIVES = "ARCHIVES";
public final static String CORP_CODE_CLASSCIRCLE = "CLASSCIRCLE";
public final static String CORP_CODE_READ = "READ";
public final static String CORP_CODE_PAY = "PAY";
public final static String CORP_CODE_LEAVE = "LEAVE";
public final static String CORP_CODE_ALBUM = "ALBUM";
public final static String CORP_CODE_ATTENDANCE = "ATTENDANCE";
public final static String CORP_CODE_NOTICE = "NOTICE";
public final static String CORP_CODE_CARD = "CARD";
public final static String CORP_CODE_COOKBOOK = "COOKBOOK";
public final static String CORP_CODE_COURSE = "COURSE";
public final static String CORP_CODE_SURVEY = "SURVEY";
public final static String CORP_CODE_SIGN = "SIGN";
public final static String CORP_CODE_LIVE = "LIVE";
public final static String CORP_CODE_DYNAMIC = "DYNAMIC";
public final static String CORP_CODE_BRACELET = "BRACELET";
}
package com.spacetech.common.utils.wechat;
import java.io.InputStream;
import org.springframework.web.multipart.MultipartFile;
public class WxPostRequst {
private String reqUrl;
private String referurl;
private String loginname;
private String loginpassword;
private String fakeid;
private String slaveuser;
private String appmsgid;
private String token;
private String cookie;
private String fileid;
private String fid;
private String tofakeid;
private String msgtype;
private String content;
private Integer requesttype;
private Integer pageidx;
private String title;
private String digest;
private String preusername;
private String sourceurl;
private MultipartFile multipartFile;
private String filename;
private String filepath;
public String getFilepath() {
return filepath;
}
public void setFilepath(String filepath) {
this.filepath = filepath;
}
private InputStream fis;
/**
* @return the reqUrl
*/
public String getReqUrl() {
return reqUrl;
}
/**
* @param reqUrl
* the reqUrl to set
*/
public void setReqUrl(String reqUrl) {
this.reqUrl = reqUrl;
}
/**
* @return the referurl
*/
public String getReferurl() {
return referurl;
}
/**
* @param referurl
* the referurl to set
*/
public void setReferurl(String referurl) {
this.referurl = referurl;
}
/**
* @return the loginname
*/
public String getLoginname() {
return loginname;
}
/**
* @param loginname
* the loginname to set
*/
public void setLoginname(String loginname) {
this.loginname = loginname;
}
/**
* @return the loginpassword
*/
public String getLoginpassword() {
return loginpassword;
}
/**
* @param loginpassword
* the loginpassword to set
*/
public void setLoginpassword(String loginpassword) {
this.loginpassword = loginpassword;
}
/**
* @return the fakeid
*/
public String getFakeid() {
return fakeid;
}
/**
* @param fakeid
* the fakeid to set
*/
public void setFakeid(String fakeid) {
this.fakeid = fakeid;
}
/**
* @return the slaveuser
*/
public String getSlaveuser() {
return slaveuser;
}
/**
* @param slaveuser
* the slaveuser to set
*/
public void setSlaveuser(String slaveuser) {
this.slaveuser = slaveuser;
}
/**
* @return the appmsgid
*/
public String getAppmsgid() {
return appmsgid;
}
/**
* @param appmsgid
* the appmsgid to set
*/
public void setAppmsgid(String appmsgid) {
this.appmsgid = appmsgid;
}
/**
* @return the token
*/
public String getToken() {
return token;
}
/**
* @param token
* the token to set
*/
public void setToken(String token) {
this.token = token;
}
/**
* @return the cookie
*/
public String getCookie() {
return cookie;
}
/**
* @param cookie
* the cookie to set
*/
public void setCookie(String cookie) {
this.cookie = cookie;
}
/**
* @return the fileid
*/
public String getFileid() {
return fileid;
}
/**
* @param fileid
* the fileid to set
*/
public void setFileid(String fileid) {
this.fileid = fileid;
}
/**
* @return the fid
*/
public String getFid() {
return fid;
}
/**
* @param fid
* the fid to set
*/
public void setFid(String fid) {
this.fid = fid;
}
/**
* @return the tofakeid
*/
public String getTofakeid() {
return tofakeid;
}
/**
* @param tofakeid
* the tofakeid to set
*/
public void setTofakeid(String tofakeid) {
this.tofakeid = tofakeid;
}
/**
* @return the msgtype
*/
public String getMsgtype() {
return msgtype;
}
/**
* @param msgtype
* the msgtype to set
*/
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getRequesttype() {
return requesttype;
}
public void setRequesttype(Integer requesttype) {
this.requesttype = requesttype;
}
public Integer getPageidx() {
return pageidx;
}
public void setPageidx(Integer pageidx) {
this.pageidx = pageidx;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDigest() {
return digest;
}
public void setDigest(String digest) {
this.digest = digest;
}
public String getPreusername() {
return preusername;
}
public void setPreusername(String preusername) {
this.preusername = preusername;
}
public String getSourceurl() {
return sourceurl;
}
public void setSourceurl(String sourceurl) {
this.sourceurl = sourceurl;
}
public MultipartFile getMultipartFile() {
return multipartFile;
}
public void setMultipartFile(MultipartFile multipartFile) {
this.multipartFile = multipartFile;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public InputStream getFis() {
return fis;
}
public void setFis(InputStream fis) {
this.fis = fis;
}
}
package com.spacetech.common.utils.wechat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.spacetech.common.ConstantVar;
import com.spacetech.common.utils.AESUtil;
import com.spacetech.common.utils.StringUtil;
import com.spacetech.common.utils.WeChatReqBean;
import com.spacetech.common.utils.WeChatRespBean;
public class WxReplyMsgUtil {
private static org.slf4j.Logger logger = LoggerFactory
.getLogger(WxReplyMsgUtil.class);
public static void valid(HttpServletRequest request,
HttpServletResponse response, WeChatReqBean reqBean, String token,
String msgType, String content) {
String echostr = request.getParameter("echostr");
try {
if (null == echostr || echostr.isEmpty()) {
responseMsg(request, response, reqBean, content);
} else {
if (checkSignature(request, token)) {
print(response, echostr);
} else {
print(response, "error");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error(e.getMessage());
}
}
// 自动回复内容
public static void responseMsg(HttpServletRequest request,
HttpServletResponse response, WeChatReqBean reqBean, String content) {
// logger.info("消息反馈腾讯:" + content);
response.setContentType("application/xml");
response.setCharacterEncoding("UTF-8");
PrintWriter out = null;
try {
out = response.getWriter();
if (null != reqBean) {
print(response, content);
} else {
print(response, "请输入您想了解的内容!");
}
out.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
if (out != null) {
out.close();
out = null;
}
}
}
/**
* @param reqBean
* @param content
* @return
*/
private static WeChatRespBean createRespBean(WeChatReqBean reqBean,
String msgType, String content) {
WeChatRespBean respBean = new WeChatRespBean();
respBean.setFromUserName(reqBean.getToUserName());
respBean.setToUserName(reqBean.getFromUserName());
respBean.setMsgType(msgType);
respBean.setCreateTime(new Date().getTime());
respBean.setContent(content);
return respBean;
}
// 微信接口验证
public static boolean checkSignature(HttpServletRequest request,
String token) {
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String[] tmpArr = { token, timestamp, nonce };
Arrays.sort(tmpArr);
String tmpStr = ArrayToString(tmpArr);
tmpStr = SHA1Encode(tmpStr);
if (tmpStr.equalsIgnoreCase(signature)) {
return true;
} else {
return false;
}
}
// 数组转字符串
public static String ArrayToString(String[] arr) {
StringBuffer bf = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
bf.append(arr[i]);
}
return bf.toString();
}
// sha1加密
public static String SHA1Encode(String sourceString) {
String resultString = null;
try {
resultString = new String(sourceString);
MessageDigest md = MessageDigest.getInstance("SHA-1");
resultString = byte2hexString(md.digest(resultString.getBytes()));
} catch (Exception ex) {
}
return resultString;
}
public static final String byte2hexString(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
}
return buf.toString().toUpperCase();
}
// 从输入流读取post参数
public static WeChatReqBean readStreamParameter(ServletInputStream in) {
Scanner scanner = new Scanner(in);
BufferedReader reader = null;
WeChatReqBean reqBean = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
// 1、获取用户发送的信息
StringBuffer sb = new StringBuffer(100);
while (scanner.hasNextLine()) {
sb.append(scanner.nextLine());
}
// 2、解析用户的信息
JAXBContext jc = JAXBContext.newInstance(WeChatReqBean.class);
Unmarshaller u = jc.createUnmarshaller();
// logger.info("***************");
// logger.info("readStreamParameter=" + sb.toString());
// logger.info("***************");
reqBean = (WeChatReqBean) u.unmarshal(new StringReader(sb
.toString()));
} catch (Exception e) {
logger.error("解析微信post内容错误:readStreamParameter" + e.getMessage(), e);
} finally {
if (scanner != null) {
scanner.close();
scanner = null;
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return reqBean;
}
public static String readRawParameter(ServletInputStream in) {
Scanner scanner = new Scanner(in);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
// 1、获取用户发送的信息
StringBuffer sb = new StringBuffer(100);
while (scanner.hasNextLine()) {
sb.append(scanner.nextLine());
}
return new String(sb.toString().getBytes(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
logger.error("错误 WeChatReqBean readRawParameter" + e.getMessage());
return "";
} finally {
if (scanner != null) {
scanner.close();
scanner = null;
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 向请求端发送返回数据
public static void print(HttpServletResponse response, String content) {
try {
response.getWriter().print(content);
response.getWriter().flush();
response.getWriter().close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 对公众平台发送给公众账号的消息加解密示例代码.
*
* @copyright Copyright (c) 1998-2014 Tencent Inc.
*/
// ------------------------------------------------------------------------
package com.spacetech.common.utils.wechat;
import java.util.Map;
/**
* XMLParse class
*
* 提供提取消息格式中的密文及生成回复消息格式的接口.
*/
class XMLParse {
/**
* 提取出xml数据包中的加密消息
*
* @param xmltext
* 待提取的xml字符串
* @return 提取出的加密消息字符串
* @throws AesException
*/
public static Object[] extract(String xmltext) throws AesException {
Object[] result = new Object[3];
try {
Map<String, String> xmlmap = XmlIterator.interatorXML(xmltext);
result[0] = 0;
result[1] = xmlmap.get("Encrypt");
result[2] = xmlmap.get("ToUserName");
return result;
} catch (Exception e) {
e.printStackTrace();
throw new AesException(AesException.ParseXmlError);
}
}
/**
* 生成xml消息
*
* @param encrypt
* 加密后的消息密文
* @param signature
* 安全签名
* @param timestamp
* 时间戳
* @param nonce
* 随机字符串
* @return 生成的xml字符串
*/
public static String generate(String encrypt, String signature,
String timestamp, String nonce) {
String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"
+ "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"
+ "<TimeStamp>%3$s</TimeStamp>\n"
+ "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";
return String.format(format, encrypt, signature, timestamp, nonce);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spacetech-cloud</artifactId>
<groupId>com.spacetech</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spacetech-service-growth</artifactId>
</project>
\ No newline at end of file
......@@ -13,10 +13,11 @@
<dependencies>
<!--nacos 配置中心-->
<dependency>
<!--使用时开启-->
<!-- <dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
</dependency>-->
<!--nacos 服务发现-->
<dependency>
......@@ -29,6 +30,12 @@
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!--dubbo-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface AgentMonitorApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* API异步调用,不需要返回给客户端
*
* @param apiMethod
* @param readonly
* @param param
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface ApiEndpointApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface AppStoreApiHub {
/**
* 调用API
* @param apiMethod
* @param readonly
* @param param
* @return
*/
String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* 异步调用API
* @param apiMethod
* @param readonly
* @param param
* @return
*/
String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface AttendanceApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface BaseDataApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* API异步调用,不需要返回给客户端
*
* @param apiMethod
* @param readonly
* @param param
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface CorpeduApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface DtalkApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* API异步调用,不需要返回给客户端
*
* @param apiMethod
* @param readonly
* @param param
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface ElectiveApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* API异步调用,不需要返回给客户端
*
* @param apiMethod
* @param readonly
* @param param
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface EvaluationApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* API异步调用,不需要返回给客户端
* @param apiMethod
* @param readonly
* @param param
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface ExamApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface ExamScoreApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface FaceApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface GrowthApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* API异步调用,不需要返回给客户端
* @param apiMethod
* @param readonly
* @param param
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface HomeworkApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface LogApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* API异步调用,不需要返回给客户端
* @param apiMethod
* @param readonly
* @param param
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface MessageApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface MetaqApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface MicrolectureApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface OaApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface OperateApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface ParentlicenseApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* API异步调用,不需要返回给客户端
* @param apiMethod
* @param readonly
* @param param
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface PayApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* API异步调用,不需要返回给客户端
* @param apiMethod
* @param readonly
* @param param
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface PortalApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface QualityApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface RecruitmentApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface RegistrationApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface SqxyApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* API异步调用,不需要返回给客户端
*
* @param apiMethod
* @param readonly
* @param param
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface SurveyApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* API异步调用,不需要返回给客户端
* @param apiMethod
* @param readonly
* @param param
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface TokenApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface UserApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface WechatApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
/**
* API异步调用,不需要返回给客户端
*
* @param apiMethod
* @param readonly
* @param param
* @return
*/
public String callApiAsync(String apiMethod, Boolean readonly, JSONObject param);
}
package com.spacetech.gateway;
import com.alibaba.fastjson.JSONObject;
public interface ZkwatcherApiHub {
/**
* 调用API
*
* @param apiMethod
* @param paramsStr
* @return
*/
public String callApi(String apiMethod, Boolean readonly, JSONObject param);
}
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