skjcmanager/skjcmanager-service-api/skjcmanager-nky-api/src/main/java/cn/gistack/nky/entity/AlarmGet.java
@@ -38,8 +38,9 @@ private String pointId; /** * 物理量id * 物理量id type,1:渗压,2:渗流,3:X位移,4:Y位移,5:Z位移 */ private String type; /** @@ -93,17 +94,22 @@ * 正向阈值 */ @TableField(value = "forward",typeHandler = FastjsonTypeHandler.class) private Object forward; private String forward; /** * 反向阈值 */ @TableField(value = "\"REVERSE\"",typeHandler = FastjsonTypeHandler.class) private Object reverse; private String reverse; /** * 系数阈值 */ @TableField(value = "ratio",typeHandler = FastjsonTypeHandler.class) private Object ratio; private String ratio; /** * 处置状态(1、已处置;2、未处置) */ private String status; } skjcmanager/skjcmanager-service-api/skjcmanager-nky-api/src/main/java/cn/gistack/nky/fegin/INkyClient.java
@@ -1,9 +1,15 @@ package cn.gistack.nky.fegin; import cn.gistack.nky.entity.AlarmGet; import cn.gistack.nky.vo.AlarmGetVO; import org.apache.ibatis.annotations.Param; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @FeignClient( value = "blade-nky", @@ -26,6 +32,10 @@ String GET_BATCH_DATA = API_PREFIX + "getBatchData"; //异常查询 String ALARM_GET_DATA = API_PREFIX + "alarmGetData"; //预警详情 String GET_ALARM_DETAIL = API_PREFIX + "getAlarmDetail"; /** * 获取arima预测结果 @@ -65,4 +75,7 @@ @GetMapping(ALARM_GET_DATA) void alarmGetData(@RequestParam("type") String type); @PostMapping(GET_ALARM_DETAIL) List<AlarmGetVO> getAlarmDetail(@RequestBody AlarmGetVO alarmGet); } skjcmanager/skjcmanager-service-api/skjcmanager-nky-api/src/main/java/cn/gistack/nky/fegin/INkyClientFallback.java
@@ -1,6 +1,10 @@ package cn.gistack.nky.fegin; import cn.gistack.nky.entity.AlarmGet; import cn.gistack.nky.vo.AlarmGetVO; import org.springframework.stereotype.Component; import java.util.List; @Component public class INkyClientFallback implements INkyClient{ @@ -35,4 +39,9 @@ public void alarmGetData(String type) { } @Override public List<AlarmGetVO> getAlarmDetail(AlarmGetVO alarmGet) { return null; } } skjcmanager/skjcmanager-service-api/skjcmanager-nky-api/src/main/java/cn/gistack/nky/vo/AlarmGetVO.java
New file @@ -0,0 +1,12 @@ package cn.gistack.nky.vo; import cn.gistack.nky.entity.AlarmGet; import lombok.Data; @Data public class AlarmGetVO extends AlarmGet { private String startTime; private String endTime; } skjcmanager/skjcmanager-service/skjcmanager-nky/src/main/java/cn/gistack/nky/feign/NkyClientImpl.java
@@ -1,16 +1,21 @@ package cn.gistack.nky.feign; import cn.gistack.nky.entity.AlarmGet; import cn.gistack.nky.fegin.INkyClient; import cn.gistack.nky.service.IAlarmGetService; import cn.gistack.nky.service.IArimaPredictService; import cn.gistack.nky.service.IHstPredictService; import cn.gistack.nky.service.INkyService; import cn.gistack.nky.vo.AlarmGetVO; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springblade.core.tenant.annotation.NonDS; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import springfox.documentation.annotations.ApiIgnore; import java.util.List; @NonDS @ApiIgnore @@ -60,4 +65,10 @@ public void alarmGetData(String type) { alarmGetService.alarmGetData(type); } @Override @PostMapping(GET_ALARM_DETAIL) public List<AlarmGetVO> getAlarmDetail(AlarmGetVO alarmGet) { return alarmGetService.getAlarmDetail(alarmGet); } } skjcmanager/skjcmanager-service/skjcmanager-nky/src/main/java/cn/gistack/nky/mapper/AlarmGetMapper.java
@@ -1,7 +1,12 @@ package cn.gistack.nky.mapper; import cn.gistack.nky.entity.AlarmGet; import cn.gistack.nky.vo.AlarmGetVO; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Param; import java.util.List; public interface AlarmGetMapper extends BaseMapper<AlarmGet> { List<AlarmGetVO> getAlarmDetail(@Param("vo") AlarmGetVO alarmGet); } skjcmanager/skjcmanager-service/skjcmanager-nky/src/main/java/cn/gistack/nky/mapper/AlarmGetMapper.xml
@@ -2,4 +2,44 @@ <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.gistack.nky.mapper.AlarmGetMapper"> <resultMap id="vo" type="cn.gistack.nky.vo.AlarmGetVO"> <id column="id" property="id"/> <result property="damId" column="dam_id"/> <result property="type" column="type"/> <result property="status" column="status"/> <result property="baojingzhi" column="baojingzhi"/> <result property="createTime" column="create_time"/> <result property="desc" column="desc"/> <result property="level" column="level"/> <result property="originId" column="origin_id"/> <result property="pointId" column="point_id"/> <result property="value" column="value"/> <result property="time" column="time"/> <result property="taskCategory" column="task_category"/> <result property="forward" column="forward" typeHandler="com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler"/> <result property="reverse" column="reverse" typeHandler="com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler"/> <result property="ratio" column="ratio" typeHandler="com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler"/> </resultMap> <select id="getAlarmDetail" resultMap="vo"> SELECT * FROM NKY_ALARM_GET WHERE 1=1 <if test="vo.startTime != null and vo.startTime != ''"> AND DATE_FORMAT(time,'%Y-%m-%d') >= #{vo.startTime} </if> <if test="vo.endTime != null and vo.endTime !='' "> AND DATE_FORMAT(time,'%Y-%m-%d') <= #{vo.endTime} </if> <if test="vo.level != null and vo.level !='' "> AND level = #{vo.level} </if> <if test="vo.status != null and vo.status !='' "> AND status = #{vo.status} </if> <if test="vo.type != null and vo.type !='' "> AND type = #{vo.type} </if> AND dam_id = #{vo.damId} </select> </mapper> skjcmanager/skjcmanager-service/skjcmanager-nky/src/main/java/cn/gistack/nky/rabbitmq/MyRabbitReceiver.java
@@ -21,11 +21,9 @@ @RabbitListener(queues = "alarm") public void processMessage(Message message) { // AlarmGet alarmGet = JSONObject.parseObject(new String(message.getBody()), AlarmGet.class); // alarmGetService.save(alarmGet); // // System.out.println("收到消息"+new String(message.getBody())); System.out.println("收到消息"+new String(message.getBody())); AlarmGet alarmGet = JSONObject.parseObject(new String(message.getBody()), AlarmGet.class); alarmGetService.save(alarmGet); } } skjcmanager/skjcmanager-service/skjcmanager-nky/src/main/java/cn/gistack/nky/service/IAlarmGetService.java
@@ -1,10 +1,15 @@ package cn.gistack.nky.service; import cn.gistack.nky.entity.AlarmGet; import cn.gistack.nky.vo.AlarmGetVO; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; public interface IAlarmGetService extends IService<AlarmGet> { void batchData(String type); void alarmGetData(String type); List<AlarmGetVO> getAlarmDetail(AlarmGetVO alarmGet); } skjcmanager/skjcmanager-service/skjcmanager-nky/src/main/java/cn/gistack/nky/service/impl/AlarmGetServiceImpl.java
@@ -9,6 +9,7 @@ import cn.gistack.nky.service.IAlarmGetService; import cn.gistack.nky.service.INkyService; import cn.gistack.nky.service.IZtApiService; import cn.gistack.nky.vo.AlarmGetVO; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; @@ -49,6 +50,11 @@ } @Override public List<AlarmGetVO> getAlarmDetail(AlarmGetVO alarmGet) { return baseMapper.getAlarmDetail(alarmGet); } /** * 获取水库集 * skjcmanager/skjcmanager-service/skjcmanager-sm/pom.xml
@@ -60,6 +60,11 @@ <artifactId>skjcmanager-alerts-api</artifactId> <version>3.0.1.RELEASE</version> </dependency> <dependency> <groupId>cn.gistack</groupId> <artifactId>skjcmanager-nky-api</artifactId> <version>3.0.1.RELEASE</version> </dependency> </dependencies> <build> skjcmanager/skjcmanager-service/skjcmanager-sm/src/main/java/cn/gistack/sm/damSecurity/controller/DamSecurityController.java
@@ -1,8 +1,13 @@ package cn.gistack.sm.damSecurity.controller; import cn.gistack.nky.entity.AlarmGet; import cn.gistack.nky.fegin.INkyClient; import cn.gistack.nky.vo.AlarmGetVO; import cn.gistack.sm.damSecurity.service.IDamSecurityService; import cn.gistack.sm.damSecurity.vo.DamSecurityStatistics; import cn.gistack.sm.damSecurity.vo.DamStationStatistics; import cn.gistack.sm.exam.entity.ExamPlan; import cn.gistack.sm.patrol.vo.PatrolTaskVO; import com.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -12,6 +17,7 @@ import org.springblade.core.mp.support.Condition; import org.springblade.core.mp.support.Query; import org.springblade.core.tool.api.R; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -22,10 +28,12 @@ @Api(tags = "大坝安全统计") @RestController @RequestMapping("/damSecurity/damSecurity") @AllArgsConstructor public class DamSecurityController extends BladeController { private final IDamSecurityService damSecurityService; @Autowired private IDamSecurityService damSecurityService; @Autowired private INkyClient nkyClient; /** * 大坝安全监测状况统计 @@ -51,4 +59,52 @@ return R.data(list); } /** * 大坝安全监测表格 * @param damStationStatistics * @return */ @ApiOperation(value = "大坝安全统计-大坝安全监测表格", notes = "大坝安全统计-大坝安全监测表格") @GetMapping(value = "/tableResCount") public R tableResCount(DamStationStatistics damStationStatistics,Query query) { IPage<DamStationStatistics> page = damSecurityService.tableResCountPage(damStationStatistics,Condition.getPage(query)); return R.data(page); } /** * 大坝安全监测表格导出 * @param damStationStatistics * @return */ @ApiOperation(value = "大坝安全统计-大坝安全监测表格导出", notes = "大坝安全统计-大坝安全监测表格导出") @GetMapping(value = "/tableResCountAll") public R tableResCountAll(DamStationStatistics damStationStatistics) { List<DamStationStatistics> list = damSecurityService.tableResCount(damStationStatistics); return R.data(list); } /** * 大坝安全监测预警详情 * @param alarmGet * @return */ @ApiOperation(value = "大坝安全统计-大坝安全监测预警详情", notes = "大坝安全统计-大坝安全监测预警详情") @GetMapping(value = "/alarmDetail") public R alarmDetail(AlarmGetVO alarmGet){ List<AlarmGetVO> list = nkyClient.getAlarmDetail(alarmGet); return R.data(list); } /** * 大坝安全监测预警异常统计 * @param damStationStatistics * @return */ @ApiOperation(value = "大坝安全统计-大坝安全监测预警异常统计", notes = "大坝安全统计-大坝安全监测预警异常统计") @GetMapping(value = "/alarmResCount") public R alarmResCount(DamStationStatistics damStationStatistics){ List<DamStationStatistics> list = damSecurityService.alarmResCount(damStationStatistics); return R.data(list); } } skjcmanager/skjcmanager-service/skjcmanager-sm/src/main/java/cn/gistack/sm/damSecurity/mapper/DamSecurityMapper.java
@@ -1,16 +1,22 @@ package cn.gistack.sm.damSecurity.mapper; import cn.gistack.sm.damSecurity.vo.DamSecurityStatistics; import cn.gistack.sm.damSecurity.vo.DamStationStatistics; import com.baomidou.mybatisplus.core.metadata.IPage; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface DamSecurityMapper { DamSecurityStatistics getSingleRegionCount(@Param("dam") DamSecurityStatistics damSecurityStatistics); List<DamSecurityStatistics> listRegionCount(@Param("dam") DamSecurityStatistics damSecurityStatistics); List<DamStationStatistics> tableResCount(@Param("dam") DamStationStatistics damStationStatistics); List<DamStationStatistics> tableResCountPage(@Param("dam")DamStationStatistics damStationStatistics, IPage<DamStationStatistics> page); List<DamStationStatistics> alarmResCount(@Param("dam") DamStationStatistics damStationStatistics); } skjcmanager/skjcmanager-service/skjcmanager-sm/src/main/java/cn/gistack/sm/damSecurity/mapper/DamSecurityMapper.xml
@@ -62,6 +62,14 @@ <if test="dam.adCode != null and dam.adCode != '' "> and (aab."ad_code" =#{dam.adCode} or aa."ad_code" = #{dam.adCode} or ab."ad_code" = #{dam.adCode} or ac."ad_code" = #{dam.adCode}) </if> <if test="dam.startTime != null and dam.startTime != ''"> AND DATE_FORMAT(time,'%Y-%m-%d') >= #{dam.startTime} </if> <if test="dam.endTime != null and dam.endTime !='' "> AND DATE_FORMAT(time,'%Y-%m-%d') <= #{dam.endTime} </if> )) errorNum ),SJZT_MD."att_ad_base" aab where 1=1 @@ -172,6 +180,14 @@ left join SJZT_MD."att_ad_base" c on b."p_ad_code" = c."ad_code" left join SJZT_MD."att_ad_base" d on c."p_ad_code" = d."ad_code" where (d."ad_code" = aab."guid" or c."ad_code" = aab."guid" or b."ad_code" = aab."guid" ) <if test="dam.startTime != null and dam.startTime != ''"> AND DATE_FORMAT(time,'%Y-%m-%d') >= #{dam.startTime} </if> <if test="dam.endTime != null and dam.endTime !='' "> AND DATE_FORMAT(time,'%Y-%m-%d') <= #{dam.endTime} </if> )) errorNum, aab."ad_name" adName , aab."guid" adCode from SJZT_MD."att_ad_base" aab where @@ -186,4 +202,248 @@ ) </select> <select id="tableResCount" resultType="cn.gistack.sm.damSecurity.vo.DamStationStatistics"> SELECT info."guid" AS resCd, info."name" AS resName, info."eng_scal" AS engScal, info."town_ad_code" AS townCode, info."town_ad_name" AS townName, info."county_ad_code" AS countyCode, info."county_ad_name" AS countyName , info."city_ad_code" AS cityCode, info."city_ad_name" AS cityName, (info.wy+info.sy+info.sl) AS total, (info.wy+info.sy+info.sl-info.errorCountNum) AS normalNum, info.errorNum AS errorNum FROM ( SELECT baseRes.*,ifnull(wy.wyStation,0) wy ,ifnull(sy.syStation,0) sy,ifnull(sl.slStation,0) sl,ifnull(alarm.errorNum,0) errorNum, ifnull(c1.errorCountNum,0) errorCountNum FROM ( SELECT a."guid", a."name", a."eng_scal", case when b."ad_grad" = 4 THEN b."ad_code" ELSE NULL END AS "town_ad_code", case when b."ad_grad" = 4 THEN b."ad_name" ELSE NULL END AS "town_ad_name", case when b."ad_grad" = 4 THEN b."order_id" ELSE NULL END AS "town_order_id", case when b."ad_grad" = 3 THEN b."ad_code" when c."ad_grad" = 3 THEN c."ad_code" END AS "county_ad_code", case when b."ad_grad" = 3 THEN b."ad_name" when c."ad_grad" = 3 THEN C."ad_name" END AS "county_ad_name", case when b."ad_grad" = 3 THEN b."order_id" when c."ad_grad" = 3 THEN C."order_id" END AS "county_order_id", case when b."ad_grad" = 2 THEN b."ad_code" when c."ad_grad" = 2 THEN c."ad_code" ELSE d."ad_code" END AS "city_ad_code", case when b."ad_grad" = 2 THEN b."ad_name" when c."ad_grad" = 2 THEN c."ad_name" ELSE d."ad_name" END AS "city_ad_name", case when b."ad_grad" = 2 THEN b."order_id" when c."ad_grad" = 2 THEN c."order_id" ELSE d."order_id" END AS "city_order_id", case when b."ad_grad" = 1 THEN b."ad_code" when c."ad_grad" = 1 THEN c."ad_code" when d."ad_grad" = 1 THEN d."ad_code" ELSE e."ad_code" END AS "province_ad_code", case when b."ad_grad" = 1 THEN b."ad_name" when c."ad_grad" = 1 THEN c."ad_name" when d."ad_grad" = 1 THEN d."ad_name" ELSE e."ad_name" END AS "province_ad_name", case when b."ad_grad" = 1 THEN b."order_id" when c."ad_grad" = 1 THEN c."order_id" when d."ad_grad" = 1 THEN d."order_id" ELSE e."order_id" END AS "province_order_id" FROM sjzt_md."att_res_base" a LEFT JOIN ( SELECT "res_cd","sys_resource" FROM (SELECT b."guid" as "res_cd",'sy' as "sys_resource" FROM sjzt_ods."dsm_spg_pztb" a LEFT JOIN SJZT_MD."att_res_base" b on a."rscd" = b."res_reg_code" UNION SELECT b."guid" as "res_cd", 'sy' as "sys_resource" FROM sjzt_ods."dsm_spg_spprmp" a LEFT JOIN SJZT_MD."att_res_base" b on a."rscd" = b."res_reg_code") WHERE "res_cd" is not null) f ON a."guid" = f."res_cd" LEFT JOIN ( SELECT "res_cd", "sys_resource" FROM (SELECT b."guid" as "res_cd", 'sl' as "sys_resource" FROM sjzt_ods."dsm_spg_spqnmp" a LEFT JOIN SJZT_MD."att_res_base" b on a."rscd" = b."res_reg_code" group by b."guid") WHERE "res_cd" is not null) G on a."guid" = g."res_cd" LEFT JOIN (SELECT "res_cd", "sys_resource" FROM (SELECT b."guid" as "res_cd", 'wy' as "sys_resource" FROM (SELECT "station_code" from sjzt_md."att_mqtt_calc_data" group by "station_code") a LEFT JOIN SJZT_MD."att_res_base" b on substr(a."station_code",0,length(a."station_code")-2) = b."guid" group by b."guid") WHERE "res_cd" is not null) h ON a."guid" = h."res_cd" LEFT JOIN sjzt_md."att_ad_base" b ON a."interior_ad_guid" = b."guid" LEFT JOIN sjzt_md."att_ad_base" c ON b."p_ad_code" = c."guid" LEFT JOIN sjzt_md."att_ad_base" d ON c."p_ad_code" = d."guid" LEFT JOIN sjzt_md."att_ad_base" e ON d."p_ad_code" = e."guid" where (f."res_cd" is not null OR g."res_cd" is not null OR h."res_cd" is not null) ) baseRes LEFT JOIN ( SELECT "res_cd",COUNT(*) wyStation FROM ( SELECT b."guid" as "res_cd",'wy' as "sys_resource" FROM (SELECT "station_code" from sjzt_md."att_mqtt_calc_data" group by "station_code") a LEFT JOIN SJZT_MD."att_res_base" b on substr(a."station_code",0,length(a."station_code")-2) = b."guid" ) GROUP BY "res_cd" ) wy ON wy."res_cd" = baseRes."guid" LEFT JOIN( SELECT "res_cd", COUNT(*) syStation FROM( SELECT b."guid" as "res_cd",'sy' as "sys_resource" FROM sjzt_ods."dsm_spg_spprmp" a LEFT JOIN SJZT_MD."att_res_base" b on a."rscd" = b."res_reg_code") GROUP BY "res_cd" ) sy ON sy."res_cd" = baseRes."guid" LEFT JOIN ( SELECT "res_cd",COUNT(*) slStation FROM ( SELECT b."guid" as "res_cd",'sl' as "sys_resource" FROM sjzt_ods."dsm_spg_spqnmp" a LEFT JOIN SJZT_MD."att_res_base" b on a."rscd" = b."res_reg_code" group by b."guid" ) GROUP BY "res_cd" ) sl ON sl."res_cd" = baseRes."guid" LEFT JOIN ( SELECT DAM_ID ,COUNT(*) errorNum FROM NKY_ALARM_GET WHERE 1=1 <if test="dam.startTime != null and dam.startTime != ''"> AND DATE_FORMAT(time,'%Y-%m-%d') >= #{dam.startTime} </if> <if test="dam.endTime != null and dam.endTime !='' "> AND DATE_FORMAT(time,'%Y-%m-%d') <= #{dam.endTime} </if> GROUP BY "DAM_ID" ) alarm ON alarm.DAM_ID = baseRes."guid" LEFT JOIN ( SELECT DAM_ID ,COUNT(*) errorCountNum FROM ( SELECT DAM_ID, COUNT(*) FROM YWXT.NKY_ALARM_GET WHERE 1=1 <if test="dam.startTime != null and dam.startTime != ''"> AND DATE_FORMAT(time,'%Y-%m-%d') >= #{dam.startTime} </if> <if test="dam.endTime != null and dam.endTime !='' "> AND DATE_FORMAT(time,'%Y-%m-%d') <= #{dam.endTime} </if> GROUP BY DAM_ID,POINT_ID ) baseCount GROUP BY DAM_ID) c1 ON c1.dam_id = baseRes."guid" LEFT JOIN SJZT_MD."att_ad_base" town ON town."guid" = "town_ad_code" LEFT JOIN SJZT_MD."att_ad_base" county ON county."guid" = town."p_ad_code" LEFT JOIN SJZT_MD."att_ad_base" city ON city."guid" = county."p_ad_code" LEFT JOIN SJZT_MD."att_ad_base" province ON province."guid" = city."p_ad_code" WHERE 1=1 <!--这里加条件--> <if test="dam.adCode != null and dam.adCode !='' "> AND (province."ad_code" = #{dam.adCode} or city."ad_code" =#{dam.adCode}or county."ad_code" = #{dam.adCode} ) </if> <if test="dam.resName != null and dam.resName !='' "> AND "name" LIKE CONCAT('%',#{dam.resName},'%') </if> ) info </select> <select id="tableResCountPage" resultType="cn.gistack.sm.damSecurity.vo.DamStationStatistics"> SELECT info."guid" AS resCd, info."name" AS resName, info."eng_scal" AS engScal, info."town_ad_code" AS townCode, info."town_ad_name" AS townName, info."county_ad_code" AS countyCode, info."county_ad_name" AS countyName , info."city_ad_code" AS cityCode, info."city_ad_name" AS cityName, (info.wy+info.sy+info.sl) AS total, (info.wy+info.sy+info.sl-info.errorCountNum) AS normalNum, info.errorNum AS errorNum FROM ( SELECT baseRes.*,ifnull(wy.wyStation,0) wy ,ifnull(sy.syStation,0) sy,ifnull(sl.slStation,0) sl,ifnull(alarm.errorNum,0) errorNum, ifnull(c1.errorCountNum,0) errorCountNum FROM ( SELECT a."guid", a."name", a."eng_scal", case when b."ad_grad" = 4 THEN b."ad_code" ELSE NULL END AS "town_ad_code", case when b."ad_grad" = 4 THEN b."ad_name" ELSE NULL END AS "town_ad_name", case when b."ad_grad" = 4 THEN b."order_id" ELSE NULL END AS "town_order_id", case when b."ad_grad" = 3 THEN b."ad_code" when c."ad_grad" = 3 THEN c."ad_code" END AS "county_ad_code", case when b."ad_grad" = 3 THEN b."ad_name" when c."ad_grad" = 3 THEN C."ad_name" END AS "county_ad_name", case when b."ad_grad" = 3 THEN b."order_id" when c."ad_grad" = 3 THEN C."order_id" END AS "county_order_id", case when b."ad_grad" = 2 THEN b."ad_code" when c."ad_grad" = 2 THEN c."ad_code" ELSE d."ad_code" END AS "city_ad_code", case when b."ad_grad" = 2 THEN b."ad_name" when c."ad_grad" = 2 THEN c."ad_name" ELSE d."ad_name" END AS "city_ad_name", case when b."ad_grad" = 2 THEN b."order_id" when c."ad_grad" = 2 THEN c."order_id" ELSE d."order_id" END AS "city_order_id", case when b."ad_grad" = 1 THEN b."ad_code" when c."ad_grad" = 1 THEN c."ad_code" when d."ad_grad" = 1 THEN d."ad_code" ELSE e."ad_code" END AS "province_ad_code", case when b."ad_grad" = 1 THEN b."ad_name" when c."ad_grad" = 1 THEN c."ad_name" when d."ad_grad" = 1 THEN d."ad_name" ELSE e."ad_name" END AS "province_ad_name", case when b."ad_grad" = 1 THEN b."order_id" when c."ad_grad" = 1 THEN c."order_id" when d."ad_grad" = 1 THEN d."order_id" ELSE e."order_id" END AS "province_order_id" FROM sjzt_md."att_res_base" a LEFT JOIN ( SELECT "res_cd","sys_resource" FROM (SELECT b."guid" as "res_cd",'sy' as "sys_resource" FROM sjzt_ods."dsm_spg_pztb" a LEFT JOIN SJZT_MD."att_res_base" b on a."rscd" = b."res_reg_code" UNION SELECT b."guid" as "res_cd", 'sy' as "sys_resource" FROM sjzt_ods."dsm_spg_spprmp" a LEFT JOIN SJZT_MD."att_res_base" b on a."rscd" = b."res_reg_code") WHERE "res_cd" is not null) f ON a."guid" = f."res_cd" LEFT JOIN ( SELECT "res_cd", "sys_resource" FROM (SELECT b."guid" as "res_cd", 'sl' as "sys_resource" FROM sjzt_ods."dsm_spg_spqnmp" a LEFT JOIN SJZT_MD."att_res_base" b on a."rscd" = b."res_reg_code" group by b."guid") WHERE "res_cd" is not null) G on a."guid" = g."res_cd" LEFT JOIN (SELECT "res_cd", "sys_resource" FROM (SELECT b."guid" as "res_cd", 'wy' as "sys_resource" FROM (SELECT "station_code" from sjzt_md."att_mqtt_calc_data" group by "station_code") a LEFT JOIN SJZT_MD."att_res_base" b on substr(a."station_code",0,length(a."station_code")-2) = b."guid" group by b."guid") WHERE "res_cd" is not null) h ON a."guid" = h."res_cd" LEFT JOIN sjzt_md."att_ad_base" b ON a."interior_ad_guid" = b."guid" LEFT JOIN sjzt_md."att_ad_base" c ON b."p_ad_code" = c."guid" LEFT JOIN sjzt_md."att_ad_base" d ON c."p_ad_code" = d."guid" LEFT JOIN sjzt_md."att_ad_base" e ON d."p_ad_code" = e."guid" where (f."res_cd" is not null OR g."res_cd" is not null OR h."res_cd" is not null) ) baseRes LEFT JOIN ( SELECT "res_cd",COUNT(*) wyStation FROM ( SELECT b."guid" as "res_cd",'wy' as "sys_resource" FROM (SELECT "station_code" from sjzt_md."att_mqtt_calc_data" group by "station_code") a LEFT JOIN SJZT_MD."att_res_base" b on substr(a."station_code",0,length(a."station_code")-2) = b."guid" ) GROUP BY "res_cd" ) wy ON wy."res_cd" = baseRes."guid" LEFT JOIN( SELECT "res_cd", COUNT(*) syStation FROM( SELECT b."guid" as "res_cd",'sy' as "sys_resource" FROM sjzt_ods."dsm_spg_spprmp" a LEFT JOIN SJZT_MD."att_res_base" b on a."rscd" = b."res_reg_code") GROUP BY "res_cd" ) sy ON sy."res_cd" = baseRes."guid" LEFT JOIN ( SELECT "res_cd",COUNT(*) slStation FROM ( SELECT b."guid" as "res_cd",'sl' as "sys_resource" FROM sjzt_ods."dsm_spg_spqnmp" a LEFT JOIN SJZT_MD."att_res_base" b on a."rscd" = b."res_reg_code" group by b."guid" ) GROUP BY "res_cd" ) sl ON sl."res_cd" = baseRes."guid" LEFT JOIN ( SELECT DAM_ID ,COUNT(*) errorNum FROM NKY_ALARM_GET WHERE 1=1 <if test="dam.startTime != null and dam.startTime != ''"> AND DATE_FORMAT(time,'%Y-%m-%d') >= #{dam.startTime} </if> <if test="dam.endTime != null and dam.endTime !='' "> AND DATE_FORMAT(time,'%Y-%m-%d') <= #{dam.endTime} </if> GROUP BY "DAM_ID" ) alarm ON alarm.DAM_ID = baseRes."guid" LEFT JOIN ( SELECT DAM_ID ,COUNT(*) errorCountNum FROM ( SELECT DAM_ID, COUNT(*) FROM YWXT.NKY_ALARM_GET WHERE 1=1 <if test="dam.startTime != null and dam.startTime != ''"> AND DATE_FORMAT(time,'%Y-%m-%d') >= #{dam.startTime} </if> <if test="dam.endTime != null and dam.endTime !='' "> AND DATE_FORMAT(time,'%Y-%m-%d') <= #{dam.endTime} </if> GROUP BY DAM_ID,POINT_ID ) baseCount GROUP BY DAM_ID) c1 ON c1.dam_id = baseRes."guid" LEFT JOIN SJZT_MD."att_ad_base" town ON town."guid" = "town_ad_code" LEFT JOIN SJZT_MD."att_ad_base" county ON county."guid" = town."p_ad_code" LEFT JOIN SJZT_MD."att_ad_base" city ON city."guid" = county."p_ad_code" LEFT JOIN SJZT_MD."att_ad_base" province ON province."guid" = city."p_ad_code" WHERE 1=1 <!--这里加条件--> <if test="dam.adCode != null and dam.adCode !='' "> AND (province."ad_code" = #{dam.adCode} or city."ad_code" =#{dam.adCode}or county."ad_code" = #{dam.adCode} ) </if> <if test="dam.resName != null and dam.resName !='' "> AND "name" LIKE CONCAT('%',#{dam.resName},'%') </if> ) info </select> <select id="alarmResCount" resultType="cn.gistack.sm.damSecurity.vo.DamStationStatistics"> SELECT arb."center_long" AS longitude, arb."center_lat" AS latitude, resCd FROM ( SELECT NAG.dam_id resCd,count(*) FROM YWXT.NKY_ALARM_GET NAG GROUP BY NAG.dam_id ) baseAlarm LEFT JOIN SJZT_MD."att_res_base" arb ON arb."guid" = baseAlarm.resCd LEFT JOIN SJZT_MD."att_ad_base" town ON town."guid" = arb."interior_ad_guid" LEFT JOIN SJZT_MD."att_ad_base" county ON county."guid" = town."p_ad_code" LEFT JOIN SJZT_MD."att_ad_base" city ON city."guid" = county."p_ad_code" LEFT JOIN SJZT_MD."att_ad_base" province ON province."guid" = city."p_ad_code" WHERE 1=1 <if test="dam.adCode != null and dam.adCode !='' "> AND (province."ad_code" =#{dam.adCode} or city."ad_code" = #{dam.adCode} or county."ad_code" = #{dam.adCode}) </if> </select> </mapper> skjcmanager/skjcmanager-service/skjcmanager-sm/src/main/java/cn/gistack/sm/damSecurity/service/IDamSecurityService.java
@@ -1,6 +1,8 @@ package cn.gistack.sm.damSecurity.service; import cn.gistack.sm.damSecurity.vo.DamSecurityStatistics; import cn.gistack.sm.damSecurity.vo.DamStationStatistics; import com.baomidou.mybatisplus.core.metadata.IPage; import java.util.List; @@ -18,4 +20,20 @@ * @return */ List<DamSecurityStatistics> listRegionCount(DamSecurityStatistics damSecurityStatistics); /** * 获取全部数据 * @param damStationStatistics * @return */ List<DamStationStatistics> tableResCount(DamStationStatistics damStationStatistics); IPage<DamStationStatistics> tableResCountPage(DamStationStatistics damStationStatistics, IPage<DamStationStatistics> page); /** * 统计预警水库列表(传回经纬度,用于首页显示) * @param damStationStatistics * @return */ List<DamStationStatistics> alarmResCount(DamStationStatistics damStationStatistics); } skjcmanager/skjcmanager-service/skjcmanager-sm/src/main/java/cn/gistack/sm/damSecurity/service/impl/DamSecurityServiceImpl.java
@@ -3,9 +3,15 @@ import cn.gistack.sm.damSecurity.mapper.DamSecurityMapper; import cn.gistack.sm.damSecurity.service.IDamSecurityService; import cn.gistack.sm.damSecurity.vo.DamSecurityStatistics; import cn.gistack.sm.damSecurity.vo.DamStationStatistics; import com.baomidou.mybatisplus.core.metadata.IPage; import org.springblade.core.tool.utils.ObjectUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.List; @Service @@ -23,4 +29,19 @@ public List<DamSecurityStatistics> listRegionCount(DamSecurityStatistics damSecurityStatistics) { return damSecurityMapper.listRegionCount(damSecurityStatistics); } @Override public List<DamStationStatistics> tableResCount(DamStationStatistics damStationStatistics) { return damSecurityMapper.tableResCount(damStationStatistics); } @Override public IPage<DamStationStatistics> tableResCountPage(DamStationStatistics damStationStatistics, IPage<DamStationStatistics> page) { return page.setRecords(damSecurityMapper.tableResCountPage(damStationStatistics,page)); } @Override public List<DamStationStatistics> alarmResCount(DamStationStatistics damStationStatistics) { return damSecurityMapper.alarmResCount(damStationStatistics); } } skjcmanager/skjcmanager-service/skjcmanager-sm/src/main/java/cn/gistack/sm/damSecurity/vo/DamSecurityStatistics.java
@@ -29,4 +29,8 @@ * 总数 */ private Integer allNum; private String startTime; private String endTime; } skjcmanager/skjcmanager-service/skjcmanager-sm/src/main/java/cn/gistack/sm/damSecurity/vo/DamStationStatistics.java
New file @@ -0,0 +1,94 @@ package cn.gistack.sm.damSecurity.vo; import lombok.Data; /** * 大坝测站数量统计 */ @Data public class DamStationStatistics { /** * 水库id */ private String resCd; /** * 水库名称 */ private String resName; /** * 地市 */ private String cityName; /** * 市编码 */ private String cityCode; /** * 区县 */ private String countyName; /** * 区县编码 */ private String countyCode; /** * 镇编码 */ private String townCode; /** * 镇名 */ private String townName; /** * 工程规模 */ private String engScal; /** * 时间 */ private String time; /** * 测点数量 */ private Integer total; /** * 正常测点数量 */ private Integer normalNum; /** * 异常测点数量 */ private Integer errorNum; /** * 行政区划编码 */ private String adCode; /** * 经度 */ private String longitude; /** * 纬度 */ private String latitude; private String startTime; private String endTime; } skjcmanager/skjcmanager-service/skjcmanager-sm/src/main/java/cn/gistack/sm/log/mapper/SmLogManageMapper.xml
@@ -41,8 +41,11 @@ <if test="vo.source !=null and vo.source !=''"> AND L.SOURCE = #{vo.source} </if> <if test="vo.daterange !=null and vo.daterange.length > 0"> AND L.CREATE_TIME >= #{vo.daterange[0]} AND L.CREATE_TIME <= #{vo.daterange[1]} <if test="vo.startTime !=null and vo.startTime !=''"> AND DATE_FORMAT(L.create_time,'%Y-%m-%d') >= #{vo.startTime} </if> <if test="vo.endTime !=null and vo.endTime !=''"> AND DATE_FORMAT(L.create_time,'%Y-%m-%d') <= #{vo.endTime} </if> ORDER BY L.CREATE_TIME DESC </select> skjcmanager/skjcmanager-service/skjcmanager-sm/src/main/java/cn/gistack/sm/log/vo/SmLogManageVO.java
@@ -10,5 +10,7 @@ */ private String createUserName; private String [] daterange; private String startTime; private String endTime; } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/constant/CimsConstants.java
New file @@ -0,0 +1,56 @@ package cn.gistack.system.user.sync.constant; /** * @author wd */ public class CimsConstants { private CimsConstants(){} /** * 字段 */ public static final String PARAM_SIGN = "sign"; public static final String PARAM_APPID = "appId"; public static final String PARAM_SYNCDATA = "syncData"; public static final String PARAM_TIMESTAMP = "timestamp"; /** * 切面值 */ public static final String AOP_API_PUSH = "apiPush"; /** * 数据源拉取 */ public static final String AOP_API_PULL = "apiPull"; /** * 密钥长度 */ public static final int SECRET_KEY_LENGTH = 32; /** * 加密编码 */ public static final String SECRET_KEY_ENCODING = "UTF-8"; /** * 数据有效时间 */ public static final int DATA_VALID_TIME = 60000; /** * 数字和字母的正则 */ public static final String SECRET_KEY_REGEX = "^[a-z0-9A-Z]+$"; /** * 服务器协议 */ public static final String REQUEST_PROTOCOL_METHOD = "POST"; } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/constant/JsonResult.java
New file @@ -0,0 +1,93 @@ package cn.gistack.system.user.sync.constant; import cn.gistack.system.user.sync.exception.ErrorCode; /** * 返回Json结果 * * @author chenzhipeng * @date 2018/2/27 */ @SuppressWarnings("rawtypes") public class JsonResult<T> { private int code = ErrorCode.SUCCESS.code; private String msg = ErrorCode.SUCCESS.msg; private T data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } public static <T> JsonResult<T> ok() { return ok(null); } public static <T> JsonResult<T> ok(T data) { JsonResult<T> result = new JsonResult<>(); result.setData(data); return result; } public static <T> JsonResult<T> okMsg(String msg){ JsonResult<T> result = new JsonResult<>(); result.setCode(ErrorCode.SUCCESS.code); result.setMsg(msg); return result; } public static <T> JsonResult<T> err(int code, String msg) { JsonResult<T> result = new JsonResult<>(); result.setCode(code); result.setMsg(msg); return result; } public static <T> JsonResult<T> err(int code, String msg, T data) { JsonResult<T> result = new JsonResult<>(); result.setCode(code); result.setMsg(msg); result.setData(data); return result; } public static <T> JsonResult<T> err(ErrorCode errorCode) { return err(errorCode, null, null); } public static <T> JsonResult<T> err(ErrorCode errorCode, String msg) { return err(errorCode, msg, null); } public static <T> JsonResult<T> err(ErrorCode errorCode, String msg, T data) { JsonResult<T> result = new JsonResult<>(); result.setCode(errorCode.code); result.setMsg(msg == null ? errorCode.msg : msg); result.setData(data); return result; } } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/controller/UserPushController.java
New file @@ -0,0 +1,78 @@ package cn.gistack.system.user.sync.controller; import cn.gistack.system.user.entity.User; import cn.gistack.system.user.service.IUserService; import cn.gistack.system.user.sync.dto.AccountBean; import cn.gistack.system.user.sync.dto.ApiPushDTO; import cn.gistack.system.user.sync.util.GenerateUtil; import cn.gistack.system.user.sync.util.SecurityUtil; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import lombok.AllArgsConstructor; import org.springblade.core.mp.support.Condition; import org.springblade.core.tenant.annotation.NonDS; import org.springblade.core.tool.api.IResultCode; import org.springblade.core.tool.api.R; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @PROJECT_NAME: skjcmanager * @DESCRIPTION: 统一登陆平台用户同步 * @USER: aix * @DATE: 2023/8/7 16:48 */ @NonDS @RestController @RequestMapping("/sync") @AllArgsConstructor public class UserPushController { private final IUserService userService; @PostMapping("/userpush") public R userPush(ApiPushDTO apiPushDTO) { String syncData = SecurityUtil.decryptAES(apiPushDTO.getSyncData(),apiPushDTO.getSign()); List<AccountBean> accountBeanList = JSONArray.parseArray(syncData, AccountBean.class); //循环list accountBeanList.forEach(accountBean -> { //判断手机号是否在库中 User params = new User(); params.setPhone(accountBean.getPrincipalId()); User one = userService.getOne(Condition.getQueryWrapper(params)); if (one == null){ //不在,看status状态,若为1则不操作。0添加进库 if (accountBean.getStatus().equals("0")){ User saveUser = new User(); //设置id为手机号 saveUser.setId(Long.parseLong(accountBean.getPrincipalId())); //账号为手机号 saveUser.setAccount(accountBean.getPrincipalId()); saveUser.setPhone(accountBean.getPrincipalId()); //设置姓名 saveUser.setRealName(accountBean.getAttributes().get("realName")); //设置部门(默认给省) saveUser.setDeptId("420000000000"); //设置角色(权限与市州水库管理业务人员一致) saveUser.setRoleId("1688732764750766082"); //设置租户id saveUser.setTenantId("000000"); userService.save(saveUser); } }else { //在,看status状态,若为1则删除用户。0更新? if (accountBean.getStatus().equals("1")){ userService.removeUser(accountBean.getPrincipalId()); } } }); return R.data(apiPushDTO.getTimestamp()); } } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/dto/AccountBean.java
New file @@ -0,0 +1,37 @@ package cn.gistack.system.user.sync.dto; import lombok.Data; import java.util.Date; import java.util.List; import java.util.Map; @Data public class AccountBean { /**正常*/ public static final String NORMAL_STATUS = "0"; /**禁用*/ public static final String DISABLE_STATUS = "1"; /**删除*/ public static final String DELETE_STATUS = "2"; /**数据同步类型 0-全量,1-增量*/ private Integer syncType; /**事件发生的时间戳*/ private long eventTimestamp; /**存入mongo时间*/ private Date createTime; /**所属任务的id,及TaskManage的主键id*/ private String taskId; /**应用id*/ private String appId; /**账号标识,主账号策略时为工号/邮箱/手机号,从账号策略时为账号身份标识字段内容*/ private String principalId; /**下发账号状态*/ private String status; private Integer sort; /**字段信息*/ private Map<String,String> attributes; private List<String> deptNums; private List<String> appRoles; } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/dto/ApiPushDTO.java
New file @@ -0,0 +1,41 @@ package cn.gistack.system.user.sync.dto; import lombok.Data; /** * @author: wd * Date: 2021/1/26 18:35 * Description : */ @Data public class ApiPushDTO { /** * 0为全量,1为增量 */ private String syncType; /** * 1为部门,2为账号 */ private String dataType; /** * 13位unix时间戳 */ private String timestamp; /** * 签名 */ private String sign; /** * 当前推送任务Id */ private String transactionId; /** *加密的部门或账号数据 */ private String syncData; } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/dto/ApiRecycleDTO.java
New file @@ -0,0 +1,10 @@ package cn.gistack.system.user.sync.dto; import lombok.Data; @Data public class ApiRecycleDTO { private String sign; private String timestamp; } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/dto/DeptBean.java
New file @@ -0,0 +1,34 @@ package cn.gistack.system.user.sync.dto; import lombok.Data; import java.util.Date; import java.util.HashMap; import java.util.Map; @Data public class DeptBean { // 正常状态:包括新增/修改/迁移 public static final String MOD_STATUS = "0"; // 异常状态:一般指删除 public static final String DEL_STATUS = "1"; /**数据同步类型 0-全量,1-增量*/ private Integer syncType; /**时间戳*/ private long eventTimestamp; /**存入mongo时间*/ private Date createTime; /**所属任务的id, 即TaskManage的id*/ private String taskId; private String appId; private String name; private String status; private String depNum; private String parentNum; private String parentNums; private Integer sort = 0; private Map<String, String> attrs = new HashMap<>(); } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/exception/BusinessException.java
New file @@ -0,0 +1,45 @@ package cn.gistack.system.user.sync.exception; /** * @author wd */ public class BusinessException extends RuntimeException { private static final long serialVersionUID = -1660410201568475030L; private Integer errCode; private String errMsg; public BusinessException(ErrorCode err) { super(err.msg); this.errCode = err.code; this.errMsg = err.msg; } public BusinessException(Integer errCode, String errMsg) { super(errMsg); this.errCode = errCode; this.errMsg = errMsg; } public BusinessException(ErrorCode err, String errMsg) { super(errMsg); this.errCode = err.code; this.errMsg = errMsg; } public BusinessException(Integer errCode, String errMsg, Throwable cause) { super(errMsg, cause); this.errCode = errCode; this.errMsg = errMsg; } public Integer getErrCode() { return errCode; } public String getErrMsg() { return errMsg; } } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/exception/ErrorCode.java
New file @@ -0,0 +1,54 @@ package cn.gistack.system.user.sync.exception; /** * 错误码对照表 * * @author wd */ public enum ErrorCode { /** * 执行成功 */ SUCCESS(1000, "成功"), /** * 错误 */ INTER_ERROR(9999, "服务器内部异常"), SIGN_CHECK_ERROR(9015, "签名校验异常"), TIMESTAMP_ERROR(9033, "时间戳校验异常"), CONTENT_EMPTY_ERROR(3011,"内容主体为空"), SECRET_KEY_ERROR(3012,"密钥格式错误"), SECRET_DECODE_ERROR(3013,"密文解密异常"), CONTENT_ENCODE_ERROR(3014,"内容加密异常"), REQUEST_SERVER_ERROR(3015,"API请求异常"), //不允许操作 ERR_9006(3016, "同步数据为空"); public int code; public String msg; ErrorCode(int code, String msg) { this.code = code; this.msg = msg; } public int getCode() { return code; } public String getStrCode() { return code+""; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/util/Base64.java
New file @@ -0,0 +1,979 @@ package cn.gistack.system.user.sync.util; import java.io.FilterOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Arrays; /** * This class consists exclusively of static methods for obtaining * encoders and decoders for the Base64 encoding scheme. The * implementation of this class supports the following types of Base64 * as specified in * <a href="http://www.ietf.org/rfc/rfc4648.txt">RFC 4648</a> and * <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>. * * <ul> * <li><a name="basic"><b>Basic</b></a> * <p> Uses "The Base64 Alphabet" as specified in Table 1 of * RFC 4648 and RFC 2045 for encoding and decoding operation. * The encoder does not add any line feed (line separator) * character. The decoder rejects data that contains characters * outside the base64 alphabet.</p></li> * * <li><a name="url"><b>URL and Filename safe</b></a> * <p> Uses the "URL and Filename safe Base64 Alphabet" as specified * in Table 2 of RFC 4648 for encoding and decoding. The * encoder does not add any line feed (line separator) character. * The decoder rejects data that contains characters outside the * base64 alphabet.</p></li> * * <li><a name="mime"><b>MIME</b></a> * <p> Uses the "The Base64 Alphabet" as specified in Table 1 of * RFC 2045 for encoding and decoding operation. The encoded output * must be represented in lines of no more than 76 characters each * and uses a carriage return {@code '\r'} followed immediately by * a linefeed {@code '\n'} as the line separator. No line separator * is added to the end of the encoded output. All line separators * or other characters not found in the base64 alphabet table are * ignored in decoding operation.</p></li> * </ul> * * <p> Unless otherwise noted, passing a {@code null} argument to a * method of this class will cause a {@link NullPointerException * NullPointerException} to be thrown. * * @author Xueming Shen * @since 1.8 */ public class Base64 { private Base64() {} /** * Returns a {@link Encoder} that encodes using the * <a href="#basic">Basic</a> type base64 encoding scheme. * * @return A Base64 encoder. */ public static Encoder getEncoder() { return Encoder.RFC4648; } /** * Returns a {@link Encoder} that encodes using the * <a href="#url">URL and Filename safe</a> type base64 * encoding scheme. * * @return A Base64 encoder. */ public static Encoder getUrlEncoder() { return Encoder.RFC4648_URLSAFE; } /** * Returns a {@link Encoder} that encodes using the * <a href="#mime">MIME</a> type base64 encoding scheme. * * @return A Base64 encoder. */ public static Encoder getMimeEncoder() { return Encoder.RFC2045; } /** * Returns a {@link Encoder} that encodes using the * <a href="#mime">MIME</a> type base64 encoding scheme * with specified line length and line separators. * * @param lineLength * the length of each output line (rounded down to nearest multiple * of 4). If {@code lineLength <= 0} the output will not be separated * in lines * @param lineSeparator * the line separator for each output line * * @return A Base64 encoder. * * @throws IllegalArgumentException if {@code lineSeparator} includes any * character of "The Base64 Alphabet" as specified in Table 1 of * RFC 2045. */ public static Encoder getMimeEncoder(int lineLength, byte[] lineSeparator) { if (lineSeparator == null) { throw new NullPointerException(); } int[] base64 = Decoder.fromBase64; for (byte b : lineSeparator) { if (base64[b & 0xff] != -1) throw new IllegalArgumentException( "Illegal base64 line separator character 0x" + Integer.toString(b, 16)); } if (lineLength <= 0) { return Encoder.RFC4648; } return new Encoder(false, lineSeparator, lineLength >> 2 << 2, true); } /** * Returns a {@link Decoder} that decodes using the * <a href="#basic">Basic</a> type base64 encoding scheme. * * @return A Base64 decoder. */ public static Decoder getDecoder() { return Decoder.RFC4648; } /** * Returns a {@link Decoder} that decodes using the * <a href="#url">URL and Filename safe</a> type base64 * encoding scheme. * * @return A Base64 decoder. */ public static Decoder getUrlDecoder() { return Decoder.RFC4648_URLSAFE; } /** * Returns a {@link Decoder} that decodes using the * <a href="#mime">MIME</a> type base64 decoding scheme. * * @return A Base64 decoder. */ public static Decoder getMimeDecoder() { return Decoder.RFC2045; } /** * This class implements an encoder for encoding byte data using * the Base64 encoding scheme as specified in RFC 4648 and RFC 2045. * * <p> Instances of {@link Encoder} class are safe for use by * multiple concurrent threads. * * <p> Unless otherwise noted, passing a {@code null} argument to * a method of this class will cause a * {@link NullPointerException NullPointerException} to * be thrown. * * @see Decoder * @since 1.8 */ public static class Encoder { private final byte[] newline; private final int linemax; private final boolean isURL; private final boolean doPadding; private Encoder(boolean isURL, byte[] newline, int linemax, boolean doPadding) { this.isURL = isURL; this.newline = newline; this.linemax = linemax; this.doPadding = doPadding; } /** * This array is a lookup table that translates 6-bit positive integer * index values into their "Base64 Alphabet" equivalents as specified * in "Table 1: The Base64 Alphabet" of RFC 2045 (and RFC 4648). */ private static final char[] toBase64 = { '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', '+', '/' }; /** * It's the lookup table for "URL and Filename safe Base64" as specified * in Table 2 of the RFC 4648, with the '+' and '/' changed to '-' and * '_'. This table is used when BASE64_URL is specified. */ private static final char[] toBase64URL = { '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', '-', '_' }; private static final int MIMELINEMAX = 76; private static final byte[] CRLF = new byte[] {'\r', '\n'}; static final Encoder RFC4648 = new Encoder(false, null, -1, true); static final Encoder RFC4648_URLSAFE = new Encoder(true, null, -1, true); static final Encoder RFC2045 = new Encoder(false, CRLF, MIMELINEMAX, true); private final int outLength(int srclen) { int len = 0; if (doPadding) { len = 4 * ((srclen + 2) / 3); } else { int n = srclen % 3; len = 4 * (srclen / 3) + (n == 0 ? 0 : n + 1); } if (linemax > 0) // line separators len += (len - 1) / linemax * newline.length; return len; } /** * Encodes all bytes from the specified byte array into a newly-allocated * byte array using the {@link Base64} encoding scheme. The returned byte * array is of the length of the resulting bytes. * * @param src * the byte array to encode * @return A newly-allocated byte array containing the resulting * encoded bytes. */ public byte[] encode(byte[] src) { int len = outLength(src.length); // dst array size byte[] dst = new byte[len]; int ret = encode0(src, 0, src.length, dst); if (ret != dst.length) return Arrays.copyOf(dst, ret); return dst; } /** * Encodes all bytes from the specified byte array using the * {@link Base64} encoding scheme, writing the resulting bytes to the * given output byte array, starting at offset 0. * * <p> It is the responsibility of the invoker of this method to make * sure the output byte array {@code dst} has enough space for encoding * all bytes from the input byte array. No bytes will be written to the * output byte array if the output byte array is not big enough. * * @param src * the byte array to encode * @param dst * the output byte array * @return The number of bytes written to the output byte array * * @throws IllegalArgumentException if {@code dst} does not have enough * space for encoding all input bytes. */ public int encode(byte[] src, byte[] dst) { int len = outLength(src.length); // dst array size if (dst.length < len) throw new IllegalArgumentException( "Output byte array is too small for encoding all input bytes"); return encode0(src, 0, src.length, dst); } /** * Encodes the specified byte array into a String using the {@link Base64} * encoding scheme. * * <p> This method first encodes all input bytes into a base64 encoded * byte array and then constructs a new String by using the encoded byte * array and the {@code ISO-8859-1} charset. * * <p> In other words, an invocation of this method has exactly the same * effect as invoking * {@code new String(encode(src), StandardCharsets.ISO_8859_1)}. * * @param src * the byte array to encode * @return A String containing the resulting Base64 encoded characters */ @SuppressWarnings("deprecation") public String encodeToString(byte[] src) { byte[] encoded = encode(src); return new String(encoded, 0, 0, encoded.length); } /** * Encodes all remaining bytes from the specified byte buffer into * a newly-allocated ByteBuffer using the {@link Base64} encoding * scheme. * * Upon return, the source buffer's position will be updated to * its limit; its limit will not have been changed. The returned * output buffer's position will be zero and its limit will be the * number of resulting encoded bytes. * * @param buffer * the source ByteBuffer to encode * @return A newly-allocated byte buffer containing the encoded bytes. */ public ByteBuffer encode(ByteBuffer buffer) { int len = outLength(buffer.remaining()); byte[] dst = new byte[len]; int ret = 0; if (buffer.hasArray()) { ret = encode0(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.arrayOffset() + buffer.limit(), dst); buffer.position(buffer.limit()); } else { byte[] src = new byte[buffer.remaining()]; buffer.get(src); ret = encode0(src, 0, src.length, dst); } if (ret != dst.length) dst = Arrays.copyOf(dst, ret); return ByteBuffer.wrap(dst); } /** * Wraps an output stream for encoding byte data using the {@link Base64} * encoding scheme. * * <p> It is recommended to promptly close the returned output stream after * use, during which it will flush all possible leftover bytes to the underlying * output stream. Closing the returned output stream will close the underlying * output stream. * * @param os * the output stream. * @return the output stream for encoding the byte data into the * specified Base64 encoded format */ public OutputStream wrap(OutputStream os) { if(os == null) { throw new NullPointerException(); } return new EncOutputStream(os, isURL ? toBase64URL : toBase64, newline, linemax, doPadding); } /** * Returns an encoder instance that encodes equivalently to this one, * but without adding any padding character at the end of the encoded * byte data. * * <p> The encoding scheme of this encoder instance is unaffected by * this invocation. The returned encoder instance should be used for * non-padding encoding operation. * * @return an equivalent encoder that encodes without adding any * padding character at the end */ public Encoder withoutPadding() { if (!doPadding) return this; return new Encoder(isURL, newline, linemax, false); } private int encode0(byte[] src, int off, int end, byte[] dst) { char[] base64 = isURL ? toBase64URL : toBase64; int sp = off; int slen = (end - off) / 3 * 3; int sl = off + slen; if (linemax > 0 && slen > linemax / 4 * 3) slen = linemax / 4 * 3; int dp = 0; while (sp < sl) { int sl0 = Math.min(sp + slen, sl); for (int sp0 = sp, dp0 = dp ; sp0 < sl0; ) { int bits = (src[sp0++] & 0xff) << 16 | (src[sp0++] & 0xff) << 8 | (src[sp0++] & 0xff); dst[dp0++] = (byte)base64[(bits >>> 18) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 12) & 0x3f]; dst[dp0++] = (byte)base64[(bits >>> 6) & 0x3f]; dst[dp0++] = (byte)base64[bits & 0x3f]; } int dlen = (sl0 - sp) / 3 * 4; dp += dlen; sp = sl0; if (dlen == linemax && sp < end) { for (byte b : newline){ dst[dp++] = b; } } } if (sp < end) { // 1 or 2 leftover bytes int b0 = src[sp++] & 0xff; dst[dp++] = (byte)base64[b0 >> 2]; if (sp == end) { dst[dp++] = (byte)base64[(b0 << 4) & 0x3f]; if (doPadding) { dst[dp++] = '='; dst[dp++] = '='; } } else { int b1 = src[sp++] & 0xff; dst[dp++] = (byte)base64[(b0 << 4) & 0x3f | (b1 >> 4)]; dst[dp++] = (byte)base64[(b1 << 2) & 0x3f]; if (doPadding) { dst[dp++] = '='; } } } return dp; } } /** * This class implements a decoder for decoding byte data using the * Base64 encoding scheme as specified in RFC 4648 and RFC 2045. * * <p> The Base64 padding character {@code '='} is accepted and * interpreted as the end of the encoded byte data, but is not * required. So if the final unit of the encoded byte data only has * two or three Base64 characters (without the corresponding padding * character(s) padded), they are decoded as if followed by padding * character(s). If there is a padding character present in the * final unit, the correct number of padding character(s) must be * present, otherwise {@code IllegalArgumentException} ( * {@code IOException} when reading from a Base64 stream) is thrown * during decoding. * * <p> Instances of {@link Decoder} class are safe for use by * multiple concurrent threads. * * <p> Unless otherwise noted, passing a {@code null} argument to * a method of this class will cause a * {@link NullPointerException NullPointerException} to * be thrown. * * @see Encoder * @since 1.8 */ public static class Decoder { private final boolean isURL; private final boolean isMIME; private Decoder(boolean isURL, boolean isMIME) { this.isURL = isURL; this.isMIME = isMIME; } /** * Lookup table for decoding unicode characters drawn from the * "Base64 Alphabet" (as specified in Table 1 of RFC 2045) into * their 6-bit positive integer equivalents. Characters that * are not in the Base64 alphabet but fall within the bounds of * the array are encoded to -1. * */ private static final int[] fromBase64 = new int[256]; static { Arrays.fill(fromBase64, -1); for (int i = 0; i < Encoder.toBase64.length; i++) fromBase64[Encoder.toBase64[i]] = i; fromBase64['='] = -2; } /** * Lookup table for decoding "URL and Filename safe Base64 Alphabet" * as specified in Table2 of the RFC 4648. */ private static final int[] fromBase64URL = new int[256]; static { Arrays.fill(fromBase64URL, -1); for (int i = 0; i < Encoder.toBase64URL.length; i++) fromBase64URL[Encoder.toBase64URL[i]] = i; fromBase64URL['='] = -2; } static final Decoder RFC4648 = new Decoder(false, false); static final Decoder RFC4648_URLSAFE = new Decoder(true, false); static final Decoder RFC2045 = new Decoder(false, true); /** * Decodes all bytes from the input byte array using the {@link Base64} * encoding scheme, writing the results into a newly-allocated output * byte array. The returned byte array is of the length of the resulting * bytes. * * @param src * the byte array to decode * * @return A newly-allocated byte array containing the decoded bytes. * * @throws IllegalArgumentException * if {@code src} is not in valid Base64 scheme */ public byte[] decode(byte[] src) { byte[] dst = new byte[outLength(src, 0, src.length)]; int ret = decode0(src, 0, src.length, dst); if (ret != dst.length) { dst = Arrays.copyOf(dst, ret); } return dst; } /** * Decodes a Base64 encoded String into a newly-allocated byte array * using the {@link Base64} encoding scheme. * * <p> An invocation of this method has exactly the same effect as invoking * {@code decode(src.getBytes(StandardCharsets.ISO_8859_1))} * * @param src * the string to decode * * @return A newly-allocated byte array containing the decoded bytes. * * @throws IllegalArgumentException * if {@code src} is not in valid Base64 scheme */ public byte[] decode(String src) { return decode(src.getBytes(Charset.forName("ISO-8859-1"))); } /** * Decodes all bytes from the input byte array using the {@link Base64} * encoding scheme, writing the results into the given output byte array, * starting at offset 0. * * <p> It is the responsibility of the invoker of this method to make * sure the output byte array {@code dst} has enough space for decoding * all bytes from the input byte array. No bytes will be be written to * the output byte array if the output byte array is not big enough. * * <p> If the input byte array is not in valid Base64 encoding scheme * then some bytes may have been written to the output byte array before * IllegalargumentException is thrown. * * @param src * the byte array to decode * @param dst * the output byte array * * @return The number of bytes written to the output byte array * * @throws IllegalArgumentException * if {@code src} is not in valid Base64 scheme, or {@code dst} * does not have enough space for decoding all input bytes. */ public int decode(byte[] src, byte[] dst) { int len = outLength(src, 0, src.length); if (dst.length < len) throw new IllegalArgumentException( "Output byte array is too small for decoding all input bytes"); return decode0(src, 0, src.length, dst); } /** * Decodes all bytes from the input byte buffer using the {@link Base64} * encoding scheme, writing the results into a newly-allocated ByteBuffer. * * <p> Upon return, the source buffer's position will be updated to * its limit; its limit will not have been changed. The returned * output buffer's position will be zero and its limit will be the * number of resulting decoded bytes * * <p> {@code IllegalArgumentException} is thrown if the input buffer * is not in valid Base64 encoding scheme. The position of the input * buffer will not be advanced in this case. * * @param buffer * the ByteBuffer to decode * * @return A newly-allocated byte buffer containing the decoded bytes * * @throws IllegalArgumentException * if {@code src} is not in valid Base64 scheme. */ public ByteBuffer decode(ByteBuffer buffer) { int pos0 = buffer.position(); try { byte[] src; int sp, sl; if (buffer.hasArray()) { src = buffer.array(); sp = buffer.arrayOffset() + buffer.position(); sl = buffer.arrayOffset() + buffer.limit(); buffer.position(buffer.limit()); } else { src = new byte[buffer.remaining()]; buffer.get(src); sp = 0; sl = src.length; } byte[] dst = new byte[outLength(src, sp, sl)]; return ByteBuffer.wrap(dst, 0, decode0(src, sp, sl, dst)); } catch (IllegalArgumentException iae) { buffer.position(pos0); throw iae; } } /** * Returns an input stream for decoding {@link Base64} encoded byte stream. * * <p> The {@code read} methods of the returned {@code InputStream} will * throw {@code IOException} when reading bytes that cannot be decoded. * * <p> Closing the returned input stream will close the underlying * input stream. * * @param is * the input stream * * @return the input stream for decoding the specified Base64 encoded * byte stream */ public InputStream wrap(InputStream is) { if(is == null) { throw new NullPointerException(); } return new DecInputStream(is, isURL ? fromBase64URL : fromBase64, isMIME); } private int outLength(byte[] src, int sp, int sl) { int[] base64 = isURL ? fromBase64URL : fromBase64; int paddings = 0; int len = sl - sp; if (len == 0) return 0; if (len < 2) { if (isMIME && base64[0] == -1) return 0; throw new IllegalArgumentException( "Input byte[] should at least have 2 bytes for base64 bytes"); } if (isMIME) { // scan all bytes to fill out all non-alphabet. a performance // trade-off of pre-scan or Arrays.copyOf int n = 0; while (sp < sl) { int b = src[sp++] & 0xff; if (b == '=') { len -= (sl - sp + 1); break; } if ((b = base64[b]) == -1) n++; } len -= n; } else { if (src[sl - 1] == '=') { paddings++; if (src[sl - 2] == '=') paddings++; } } if (paddings == 0 && (len & 0x3) != 0) paddings = 4 - (len & 0x3); return 3 * ((len + 3) / 4) - paddings; } private int decode0(byte[] src, int sp, int sl, byte[] dst) { int[] base64 = isURL ? fromBase64URL : fromBase64; int dp = 0; int bits = 0; int shiftto = 18; // pos of first byte of 4-byte atom while (sp < sl) { int b = src[sp++] & 0xff; if ((b = base64[b]) < 0) { if (b == -2) { // padding byte '=' // = shiftto==18 unnecessary padding // x= shiftto==12 a dangling single x // x to be handled together with non-padding case // xx= shiftto==6&&sp==sl missing last = // xx=y shiftto==6 last is not = if (shiftto == 6 && (sp == sl || src[sp++] != '=') || shiftto == 18) { throw new IllegalArgumentException( "Input byte array has wrong 4-byte ending unit"); } break; } if (isMIME) // skip if for rfc2045 continue; else throw new IllegalArgumentException( "Illegal base64 character " + Integer.toString(src[sp - 1], 16)); } bits |= (b << shiftto); shiftto -= 6; if (shiftto < 0) { dst[dp++] = (byte)(bits >> 16); dst[dp++] = (byte)(bits >> 8); dst[dp++] = (byte)(bits); shiftto = 18; bits = 0; } } // reached end of byte array or hit padding '=' characters. if (shiftto == 6) { dst[dp++] = (byte)(bits >> 16); } else if (shiftto == 0) { dst[dp++] = (byte)(bits >> 16); dst[dp++] = (byte)(bits >> 8); } else if (shiftto == 12) { // dangling single "x", incorrectly encoded. throw new IllegalArgumentException( "Last unit does not have enough valid bits"); } // anything left is invalid, if is not MIME. // if MIME, ignore all non-base64 character while (sp < sl) { if (isMIME && base64[src[sp++]] < 0) continue; throw new IllegalArgumentException( "Input byte array has incorrect ending byte at " + sp); } return dp; } } /* * An output stream for encoding bytes into the Base64. */ private static class EncOutputStream extends FilterOutputStream { private int leftover = 0; private int b0, b1, b2; private boolean closed = false; private final char[] base64; // byte->base64 mapping private final byte[] newline; // line separator, if needed private final int linemax; private final boolean doPadding;// whether or not to pad private int linepos = 0; EncOutputStream(OutputStream os, char[] base64, byte[] newline, int linemax, boolean doPadding) { super(os); this.base64 = base64; this.newline = newline; this.linemax = linemax; this.doPadding = doPadding; } @Override public void write(int b) throws IOException { byte[] buf = new byte[1]; buf[0] = (byte)(b & 0xff); write(buf, 0, 1); } private void checkNewline() throws IOException { if (linepos == linemax) { out.write(newline); linepos = 0; } } @Override public void write(byte[] b, int off, int len) throws IOException { if (closed) throw new IOException("Stream is closed"); if (off < 0 || len < 0 || off + len > b.length) throw new ArrayIndexOutOfBoundsException(); if (len == 0) return; if (leftover != 0) { if (leftover == 1) { b1 = b[off++] & 0xff; len--; if (len == 0) { leftover++; return; } } b2 = b[off++] & 0xff; len--; checkNewline(); out.write(base64[b0 >> 2]); out.write(base64[(b0 << 4) & 0x3f | (b1 >> 4)]); out.write(base64[(b1 << 2) & 0x3f | (b2 >> 6)]); out.write(base64[b2 & 0x3f]); linepos += 4; } int nBits24 = len / 3; leftover = len - (nBits24 * 3); while (nBits24-- > 0) { checkNewline(); int bits = (b[off++] & 0xff) << 16 | (b[off++] & 0xff) << 8 | (b[off++] & 0xff); out.write(base64[(bits >>> 18) & 0x3f]); out.write(base64[(bits >>> 12) & 0x3f]); out.write(base64[(bits >>> 6) & 0x3f]); out.write(base64[bits & 0x3f]); linepos += 4; } if (leftover == 1) { b0 = b[off++] & 0xff; } else if (leftover == 2) { b0 = b[off++] & 0xff; b1 = b[off++] & 0xff; } } @Override public void close() throws IOException { if (!closed) { closed = true; if (leftover == 1) { checkNewline(); out.write(base64[b0 >> 2]); out.write(base64[(b0 << 4) & 0x3f]); if (doPadding) { out.write('='); out.write('='); } } else if (leftover == 2) { checkNewline(); out.write(base64[b0 >> 2]); out.write(base64[(b0 << 4) & 0x3f | (b1 >> 4)]); out.write(base64[(b1 << 2) & 0x3f]); if (doPadding) { out.write('='); } } leftover = 0; out.close(); } } } /* * An input stream for decoding Base64 bytes */ private static class DecInputStream extends InputStream { private final InputStream is; private final boolean isMIME; private final int[] base64; // base64 -> byte mapping private int bits = 0; // 24-bit buffer for decoding private int nextin = 18; // next available "off" in "bits" for input; // -> 18, 12, 6, 0 private int nextout = -8; // next available "off" in "bits" for output; // -> 8, 0, -8 (no byte for output) private boolean eof = false; private boolean closed = false; DecInputStream(InputStream is, int[] base64, boolean isMIME) { this.is = is; this.base64 = base64; this.isMIME = isMIME; } private byte[] sbBuf = new byte[1]; @Override public int read() throws IOException { return read(sbBuf, 0, 1) == -1 ? -1 : sbBuf[0] & 0xff; } @Override public int read(byte[] b, int off, int len) throws IOException { if (closed) throw new IOException("Stream is closed"); if (eof && nextout < 0) // eof and no leftover return -1; if (off < 0 || len < 0 || len > b.length - off) throw new IndexOutOfBoundsException(); int oldOff = off; if (nextout >= 0) { // leftover output byte(s) in bits buf do { if (len == 0) return off - oldOff; b[off++] = (byte)(bits >> nextout); len--; nextout -= 8; } while (nextout >= 0); bits = 0; } while (len > 0) { int v = is.read(); if (v == -1) { eof = true; if (nextin != 18) { if (nextin == 12) throw new IOException("Base64 stream has one un-decoded dangling byte."); // treat ending xx/xxx without padding character legal. // same logic as v == '=' below b[off++] = (byte)(bits >> (16)); len--; if (nextin == 0) { // only one padding byte if (len == 0) { // no enough output space bits >>= 8; // shift to lowest byte nextout = 0; } else { b[off++] = (byte) (bits >> 8); } } } if (off == oldOff) return -1; else return off - oldOff; } if (v == '=') { // padding byte(s) // = shiftto==18 unnecessary padding // x= shiftto==12 dangling x, invalid unit // xx= shiftto==6 && missing last '=' // xx=y or last is not '=' if (nextin == 18 || nextin == 12 || nextin == 6 && is.read() != '=') { throw new IOException("Illegal base64 ending sequence:" + nextin); } b[off++] = (byte)(bits >> (16)); len--; if (nextin == 0) { // only one padding byte if (len == 0) { // no enough output space bits >>= 8; // shift to lowest byte nextout = 0; } else { b[off++] = (byte) (bits >> 8); } } eof = true; break; } if ((v = base64[v]) == -1) { if (isMIME) // skip if for rfc2045 continue; else throw new IOException("Illegal base64 character " + Integer.toString(v, 16)); } bits |= (v << nextin); if (nextin == 0) { nextin = 18; // clear for next nextout = 16; while (nextout >= 0) { b[off++] = (byte)(bits >> nextout); len--; nextout -= 8; if (len == 0 && nextout >= 0) { // don't clean "bits" return off - oldOff; } } bits = 0; } else { nextin -= 6; } } return off - oldOff; } @Override public int available() throws IOException { if (closed) throw new IOException("Stream is closed"); return is.available(); // TBD: } @Override public void close() throws IOException { if (!closed) { closed = true; is.close(); } } } } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/util/GenerateUtil.java
New file @@ -0,0 +1,53 @@ package cn.gistack.system.user.sync.util; import cn.gistack.system.user.sync.dto.AccountBean; import cn.gistack.system.user.sync.dto.ApiPushDTO; import java.util.ArrayList; import java.util.List; public class GenerateUtil { public static String generateSyncData(){ String syncData = "[\n" + "\t\t{\n" + "\t\t\t\"syncType\": 0,\n" + "\t\t\t\"eventTimestamp\": 1640160139389,\n" + "\t\t\t\"createTime\": 1640160139473,\n" + "\t\t\t\"taskId\": \"fc5fbc9f603c46219d1c07d02f16c6e7\",\n" + "\t\t\t\"appId\": \"659240c7ae18415e945cdab21e822cd3\",\n" + "\t\t\t\"principalId\": \"19998851452\",\n" + "\t\t\t\"status\": \"1\",\n" + "\t\t\t\"attributes\": {\n" + "\t\t\t\t\"deptNums\": \",csbm1,\",\n" + "\t\t\t\t\"address\": \"北京市海淀区\",\n" + "\t\t\t\t\"gender\": \"男\",\n" + "\t\t\t\t\"realName\": \"cszh1\"\n" + "\t\t\t},\n" + "\t\t\t\"deptNums\": [\n" + "\t\t\t\t\"csbm1\"\n" + "\t\t\t],\n" + "\t\t\t\"appRoles\": []\n" + "\t\t}\n" + "\t]\n"; String s = SecurityUtil.encryptAES(syncData, "20AF281AC7F82868AB0953E6868123A9"); return s; } public static ApiPushDTO generateApiPushDTO(){ ApiPushDTO apiPushDTO = new ApiPushDTO(); apiPushDTO.setSyncType("0"); apiPushDTO.setDataType("2"); apiPushDTO.setTimestamp("1640160139576"); apiPushDTO.setSign("20AF281AC7F82868AB0953E6868123A9"); apiPushDTO.setTransactionId("fc5fbc9f603c46219d1c07d02f16c6e7"); apiPushDTO.setSyncData(generateSyncData()); System.out.println(apiPushDTO); return apiPushDTO; } } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/util/MD5Util.java
New file @@ -0,0 +1,48 @@ package cn.gistack.system.user.sync.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * MD5加密 * @author wd */ public class MD5Util { /** * 定义char数组,16进制对应的基本字符 */ private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** * md5加密 * @param str 需要加密的数据 * @return 加密结果 */ public static String getMD5String(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messageDigest.update(str.getBytes()); return byteArray2HexString(messageDigest.digest()); } /** * MD5加密结果(由byte转换成String) * @param bytes md5加密后得到的数组 * @return md5加密结果 */ private static String byteArray2HexString(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(HEX_DIGITS[(b & 0xf0) >> 4]).append(HEX_DIGITS[(b & 0x0f)]); } return sb.toString(); } } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/util/SecurityUtil.java
New file @@ -0,0 +1,193 @@ package cn.gistack.system.user.sync.util; import cn.gistack.system.user.sync.constant.CimsConstants; import cn.gistack.system.user.sync.exception.BusinessException; import cn.gistack.system.user.sync.exception.ErrorCode; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; /** * AES加密解密 * @author wd */ public class SecurityUtil { /** * AES加密 * * @param content 明文 * @return 密文 */ public static String encryptAES(String content, String secretKey) { checkParam(content,secretKey); //AES加密 String encryptResultStr = encrypt(content, secretKey); //BASE64位加密 encryptResultStr = ebotongEncrypto(encryptResultStr); return encryptResultStr; } /** * AES解密 * * @param encryptResultStr 密文 * @return 明文 */ public static String decryptAES(String encryptResultStr,String secretKey) { checkParam(encryptResultStr,secretKey); try { // BASE64位解密 String decrpt = ebotongDecrypto(encryptResultStr); byte[] decryptFrom = hexToByteArray(decrpt); //AES解密 byte[] decryptResult = decrypt(decryptFrom, secretKey); return new String(decryptResult); } catch (Exception e) { e.printStackTrace(); // 当密文不规范时会报错,可忽略,但调用的地方需要考虑 throw new BusinessException(ErrorCode.CONTENT_EMPTY_ERROR); } } /** * 校验参数 */ private static void checkParam(String encryptResultStr,String secretKey){ if (isBlank(encryptResultStr)) { throw new BusinessException(ErrorCode.CONTENT_EMPTY_ERROR); } if (secretKey.length() != CimsConstants.SECRET_KEY_LENGTH || !secretKey.matches(CimsConstants.SECRET_KEY_REGEX)) { throw new BusinessException(ErrorCode.SECRET_KEY_ERROR); } } /** * 加密 * * @param content 需要加密的内容 * @param password 加密密码 * @return */ private static String encrypt(String content, String password) { try { byte[] raw = password.getBytes(CimsConstants.SECRET_KEY_ENCODING); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] byteRresult = cipher.doFinal(content.getBytes(CimsConstants.SECRET_KEY_ENCODING)); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteRresult.length; i++) { String hex = Integer.toHexString(byteRresult[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } catch (Exception e) { throw new BusinessException(ErrorCode.CONTENT_ENCODE_ERROR); } } /** * 解密 * * @param content 待解密内容 * @param password 解密密钥 * @return */ private static byte[] decrypt(byte[] content, String password) { try { byte[] raw = password.getBytes(CimsConstants.SECRET_KEY_ENCODING); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] result = cipher.doFinal(content); return result; } catch (Exception e) { e.printStackTrace(); throw new BusinessException(ErrorCode.SECRET_DECODE_ERROR); } } /** * hex字符串转byte数组 * @param inHex 待转换的Hex字符串 * @return 转换后的byte数组结果 */ private static byte[] hexToByteArray(String inHex){ int hexlen = inHex.length(); byte[] result; if (hexlen % 2 == 1){ //奇数 hexlen++; result = new byte[(hexlen/2)]; inHex="0"+inHex; }else { //偶数 result = new byte[(hexlen/2)]; } int j=0; for (int i = 0; i < hexlen; i+=2){ result[j] = hexToByte(inHex.substring(i,i+2)); j++; } return result; } /** * Hex字符串转byte * @param inHex 待转换的Hex字符串 * @return 转换后的byte */ private static byte hexToByte(String inHex){ return (byte)Integer.parseInt(inHex,16); } /** * Base64加密字符串 */ private static String ebotongEncrypto(String str) { String result = str; if (str != null && str.length() > 0) { try { byte[] encodeByte = str.getBytes(CimsConstants.SECRET_KEY_ENCODING); result = Base64.getEncoder().encodeToString(encodeByte); } catch (Exception e) { e.printStackTrace(); } } // base64加密超过一定长度会自动换行 需要去除换行符 return result.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", ""); } /** * Base64解密字符串 */ private static String ebotongDecrypto(String str) { byte[] encodeByte = Base64.getDecoder().decode(str); return new String(encodeByte); } /** * 判断字符串是否为空 * @param cs * @return */ private static boolean isBlank(final CharSequence cs) { int strLen; if (cs == null || (strLen = cs.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; } } skjcmanager/skjcmanager-service/skjcmanager-user/src/main/java/cn/gistack/system/user/sync/util/SignUtil.java
New file @@ -0,0 +1,44 @@ package cn.gistack.system.user.sync.util; import cn.gistack.system.user.sync.constant.CimsConstants; import java.util.Map; import java.util.TreeMap; /** * @author: wd * Date: 2020/12/7 10:26 * Description : API标准化生成sign的类 */ public class SignUtil { /** * 生成当前时间戳 * @return */ public static Long getCurrentTimeStamp(){ return System.currentTimeMillis(); } /** * 生成接口签名 */ public static String getSign(String appId, Long timeStamp, String key, String url, String method, Map<String, String> params){ StringBuilder sb = new StringBuilder(); params.remove(CimsConstants.PARAM_APPID); params.remove(CimsConstants.PARAM_SIGN); params.remove(CimsConstants.PARAM_TIMESTAMP); params.remove(CimsConstants.PARAM_SYNCDATA); Map<String, String> sortParams = new TreeMap<>(params); sb.append(appId).append(timeStamp); for (Map.Entry<String, String> entry : sortParams.entrySet()) { String value = entry.getValue() == null ? "" : entry.getValue().trim(); sb.append(value); } sb.append(key).append(url).append(method); return MD5Util.getMD5String(sb.toString()).toUpperCase(); } }