Java tutorial
package com.taikang.dic.ltci.service.impl; import java.io.UnsupportedEncodingException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.taikang.dic.ltci.api.model.AgencyDTO; import com.taikang.dic.ltci.api.model.AgencyHistoryDTO; import com.taikang.dic.ltci.api.model.AttachmentDTO; import com.taikang.dic.ltci.api.model.ResultDTO; import com.taikang.dic.ltci.common.enumeration.ActionTypeEnum; import com.taikang.dic.ltci.common.enumeration.AgencyStateEnum; import com.taikang.dic.ltci.common.enumeration.ExecutionStatusEnum; import com.taikang.dic.ltci.common.enumeration.IsValidEnum; import com.taikang.dic.ltci.common.enumeration.ObjectTypeEnum; import com.taikang.dic.ltci.common.enumeration.OperationTypeEnum; import com.taikang.dic.ltci.common.enumeration.StatusCodeEnum; import com.taikang.dic.ltci.common.enumeration.TransportTypeEnum; import com.taikang.dic.ltci.common.exception.ThrowsException; import com.taikang.dic.ltci.common.util.DateFormat; import com.taikang.dic.ltci.common.util.DateFormatUtil; import com.taikang.dic.ltci.common.util.Encodes; import com.taikang.dic.ltci.common.util.FileTypeDecideUtil; import com.taikang.dic.ltci.common.util.IPUtil; import com.taikang.dic.ltci.common.util.SpringContextUtil; import com.taikang.dic.ltci.common.util.UrlUtil; import com.taikang.dic.ltci.controller.AgencyHistoryController; import com.taikang.dic.ltci.dao.AgencyHistoryDAO; import com.taikang.dic.ltci.dao.AgencyStaffFileRDAO; import com.taikang.dic.ltci.model.AgencyHistoryDO; import com.taikang.dic.ltci.model.AgencyHistoryDOExample; import com.taikang.dic.ltci.model.AgencyHistoryDOExample.Criteria; import com.taikang.dic.ltci.model.AgencyStaffFileRDO; import com.taikang.dic.ltci.model.BaseModel; import com.taikang.dic.ltci.model.MqFailMessageLogDO; import com.taikang.dic.ltci.mqmodel.AgencyInterfaceParam; import com.taikang.dic.ltci.mqmodel.MqBaseModel; import com.taikang.dic.ltci.serverClient.AttachmentServiceClient; import com.taikang.dic.ltci.service.IAgencyInterfaceService; import com.taikang.dic.ltci.service.IMqFailMessageLogService; import com.taikang.dic.ltci.service.IMqMessageLogService; /** * ?service ???????? * * @author itw_muwg */ @Service public class AgencyInterfaceServiceImpl implements IAgencyInterfaceService { private Logger logger = LoggerFactory.getLogger(AgencyInterfaceServiceImpl.class); @Autowired private RabbitTemplate rabbitTemplate; @Autowired private AgencyHistoryDAO agencyHistoryDao; @Autowired private AgencyStaffFileRDAO agencyStaffFileRDAO; @Autowired private IMqMessageLogService messageLogService; @Autowired private IMqFailMessageLogService failMessageLogService; @Autowired private UrlUtil urlUtil; @Autowired private AttachmentServiceClient attachmentServiceClient; @Autowired private SpringContextUtil springContextUtil; private static char[] org = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; private static final String ROUTING_KEY = "jingmen"; @Value("${systemCharset}") private String systemCharset; @Value("${systemCode}") private String systemCode; //??query @Value("${ltci.orgApplication.queue}") private String orgApplicationQueueName; //???? @Value("${ltci.orgApplication.messageCode}") private String orgApplicationMessageCode; //??exchange @Value("${ltci.orgAcceptResult.exchange}") private String orgAcceptResultExchange; //???? @Value("${ltci.orgAcceptResult.messageCode}") private String orgAcceptResultMessageCode; //exchange @Value("${ltci.orgApproveResult.exchange}") private String orgApproveResultExchange; //?? @Value("${ltci.orgApproveResult.messageCode}") private String orgApproveResultMessageCode; //?exchange @Value("${ltci.orgChangeResult.exchange}") private String orgChangeResultExchange; //??? @Value("${ltci.orgChangeResult.messageCode}") private String orgChangeResultMessageCode; /** * ??mq?->? mq? * * @author itw_muwg */ @RabbitListener(queues = "${ltci.orgApplication.queue}") @Override public void getorgApplication(byte[] bytes) { logger.debug("=======ReconsiderServiceImpl getReconsiderReceive========="); String message = null; try { message = new String(bytes, systemCharset); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); return; } logger.info("=======mq " + orgApplicationQueueName + "???========="); //? parseMessage(message); } /** * ??? * * @param message */ @Override public int parseMessage(String message) { //??MqBaseModel MqBaseModel mqBaseModel = JSONObject.parseObject(message, MqBaseModel.class); try { //messageCode? if (orgApplicationMessageCode.equals(mqBaseModel.getMessageCode())) { //idtype? ?? boolean has = messageLogService.isHas(mqBaseModel.getBusinessSerialid()); if (has) { logger.info("======id?" + mqBaseModel.getBusinessSerialid() + "????============="); return ExecutionStatusEnum.SUCCESS.getValue(); } //? JSONObject data = JSONObject.parseObject(String.valueOf(mqBaseModel.getData())); String areaCode = getAreaCode(data); if (ActionTypeEnum.CREATE.getValue().equals(data.getString(AgencyInterfaceParam.ACTION_TYPE)) && StringUtils.isBlank(areaCode)) { logger.info("======id?" + mqBaseModel.getBusinessSerialid() + "??============="); return ExecutionStatusEnum.SUCCESS.getValue(); } //?DO AgencyHistoryDO agencyHistoryDO = data2AgencyHistoryDO(data); //???? AgencyHistoryDOExample example = new AgencyHistoryDOExample(); Criteria criteria = example.createCriteria(); criteria.andOrgCodeEqualTo(agencyHistoryDO.getOrgCode()); List<Integer> states = new ArrayList<>(); states.add(AgencyStateEnum.STATE_NO_ACCEPT.getValue()); states.add(AgencyStateEnum.STATE_ACCEPT.getValue()); criteria.andAgencyStateIn(states); List<AgencyHistoryDO> list = agencyHistoryDao.selectByExample(example); //spring?bean AgencyInterfaceServiceImpl bean = springContextUtil.getApplicationContext() .getBean(AgencyInterfaceServiceImpl.class); //? if (list != null && list.isEmpty()) { //? bean.saveOrg(mqBaseModel.getBusinessSerialid(), data, agencyHistoryDO, message); } logger.info("=====?mq ?? ??=========="); } return ExecutionStatusEnum.SUCCESS.getValue(); } catch (Exception e) { // logger.error("===?mq???===", e); if (StringUtils.isNotBlank(mqBaseModel.getBusinessSerialid())) { MqFailMessageLogDO failLog = new MqFailMessageLogDO(); failLog.setId(mqBaseModel.getBusinessSerialid()); failLog.setTransportType(TransportTypeEnum.ASYNCHRONIZE.getValue()); //? failLog.setOperationType(OperationTypeEnum.RECEIVE.getValue()); //?? failLog.setQueryName(orgApplicationQueueName); failLog.setContent(message); failLog.setErrorMessage(e.getMessage()); failLog.setCreateTime(new Date()); failLog.setHttpAction(HttpMethod.POST.name()); // ?url failLog.setRetryUrl(urlUtil.getBaseUrl() + AgencyHistoryController.RETRY_URL); failMessageLogService.saveOrUpdateFailLog(failLog); } return ExecutionStatusEnum.FAILD.getValue(); } } @Transactional public void saveOrg(String businessSerialid, JSONObject data, AgencyHistoryDO agencyHistoryDO, String message) { //?? messageLogService.receiveMqMessageLog(businessSerialid, orgApplicationQueueName, message); agencyHistoryDao.insertSelective(agencyHistoryDO); //? if (ActionTypeEnum.CREATE.getValue().equals(data.getString(AgencyInterfaceParam.ACTION_TYPE)) && data.getJSONArray(AgencyInterfaceParam.ACCESSORY) != null) { saveAccessory(data, agencyHistoryDO); } if (ActionTypeEnum.UPDATE.getValue().equals(data.getString(AgencyInterfaceParam.ACTION_TYPE))) { //??? ?? AgencyHistoryDTO agencyHistory = new AgencyHistoryDTO(); agencyHistory.setOrgCode(agencyHistoryDO.getOrgCode()); agencyHistory.setOperatedTime(DateFormatUtil.dateToTimeStr(new Date())); agencyHistory.setAgencyState(AgencyStateEnum.STATE_ACCEPT.getValue()); sendOrgAcceptResult(agencyHistory); } } private void saveAccessory(JSONObject data, AgencyHistoryDO agencyHistoryDO) { JSONArray jsonArray = data.getJSONArray(AgencyInterfaceParam.ACCESSORY); for (int i = 0; i < jsonArray.size(); i++) { JSONObject json = jsonArray.getJSONObject(i); String fileType = FileTypeDecideUtil.getFileType(json.getString(AgencyInterfaceParam.FILE_TYPE)); AttachmentDTO dto = new AttachmentDTO(); dto.setContent(Encodes.encodeBase64(json.getBytes(AgencyInterfaceParam.ACCESSORY_INFO))); dto.setFileName(json.getString(AgencyInterfaceParam.FILE_NAME)); dto.setSuffix(json.getString(AgencyInterfaceParam.FILE_TYPE)); dto.setFileType(fileType); ResultDTO resultDTO = attachmentServiceClient.addAttachment(dto); if (resultDTO == null || !resultDTO.getStatus().equals(StatusCodeEnum.CREATED.getValue())) { throw new ThrowsException("???"); } JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(resultDTO.getDatas())); String fileId = jsonObject.getString("attachmentid"); AgencyStaffFileRDO agencyStaffFile = new AgencyStaffFileRDO(); agencyStaffFile.setId(BaseModel.getUUID()); agencyStaffFile.setAccessoryType(json.getString(AgencyInterfaceParam.ACCESSORY_TYPE)); agencyStaffFile.setObjType(ObjectTypeEnum.ORG.getValue()); agencyStaffFile.setCode(agencyHistoryDO.getAgencyCode()); agencyStaffFile.setHistoryId(agencyHistoryDO.getSerialNum()); agencyStaffFile.setFileId(fileId); agencyStaffFile.setFileName(json.getString(AgencyInterfaceParam.FILE_NAME)); agencyStaffFile.setFileType(json.getString(AgencyInterfaceParam.FILE_TYPE)); agencyStaffFile.setIsValid(IsValidEnum.NO_DELETE.getValue()); agencyStaffFileRDAO.insertSelective(agencyStaffFile); } } private String getAreaCode(JSONObject data) { String areaCode = data.getString(AgencyInterfaceParam.AREA_CODE); if (StringUtils.isBlank(areaCode)) { areaCode = data.getString(AgencyInterfaceParam.CITY_CODE); } if (StringUtils.isBlank(areaCode)) { areaCode = data.getString(AgencyInterfaceParam.PROVINCE_CODE); } return areaCode; } private AgencyHistoryDO data2AgencyHistoryDO(JSONObject data) { AgencyHistoryDO agencyHistory = new AgencyHistoryDO(); /** ?1:?2:????) */ agencyHistory.setActionType(data.getString(AgencyInterfaceParam.ACTION_TYPE)); /** ???) */ agencyHistory.setOrgCode(data.getString(AgencyInterfaceParam.ORG_CODE)); /** ?ID??,? */ agencyHistory.setAgencyCode(data.getString(AgencyInterfaceParam.UNIQUE_NUMBER)); /** ?? */ agencyHistory.setAgencyName(data.getString(AgencyInterfaceParam.ORG_NAME)); /** ?? */ agencyHistory.setProvinceCode(data.getString(AgencyInterfaceParam.PROVINCE_CODE)); /** ? */ agencyHistory.setCityCode(data.getString(AgencyInterfaceParam.CITY_CODE)); /** ? */ agencyHistory.setAreaCode(data.getString(AgencyInterfaceParam.AREA_CODE)); /** ? */ agencyHistory.setAgencyAddressDetail(data.getString(AgencyInterfaceParam.AGENCY_ADDRESSD_DETAIL)); /** ?(1??;2????;3???;4??;99?) */ agencyHistory.setAgencyLevel(data.getInteger(AgencyInterfaceParam.ORG_LEVEL)); /** (00??;10?) */ agencyHistory.setAgencyType(data.getString(AgencyInterfaceParam.ORG_TYPE)); /** ?()(1??;2???;3??) ?4? */ if (data.getString(AgencyInterfaceParam.ORG_TYPE) != null && data.getString(AgencyInterfaceParam.ORG_TYPE).contains("10")) { agencyHistory.setAgencyServiceType(data.getString(AgencyInterfaceParam.ORG_SERVICE_TYPE) == null ? "4" : data.getString(AgencyInterfaceParam.ORG_SERVICE_TYPE) + ",4"); } else { agencyHistory.setAgencyServiceType(data.getString(AgencyInterfaceParam.ORG_SERVICE_TYPE)); } /** ?? */ agencyHistory.setAgencyServiceContact(data.getString(AgencyInterfaceParam.ORG_SERVICE_CONTACT)); /** ??? */ agencyHistory.setAgencyContactPhone(data.getString(AgencyInterfaceParam.ORG_CONTACT_PHONE)); /** ?? */ agencyHistory.setAgencyContactEmail(data.getString(AgencyInterfaceParam.ORG_CONTACT_EMAIL)); /** ??? */ agencyHistory.setPracticeLicense(data.getString(AgencyInterfaceParam.PRACTICE_LICENSE)); /** ?1??;2???;3??;4???;5???;6???;7?? */ agencyHistory.setOwnershipForm(data.getInteger(AgencyInterfaceParam.OWNERSHIP_FORM)); /** */ agencyHistory.setLegalRepresentative(data.getString(AgencyInterfaceParam.LEGAL_REPRESENTATIVE)); /** ? */ agencyHistory.setLegalPhoneNo(data.getString(AgencyInterfaceParam.LEGAL_PHONE)); /** ?? */ agencyHistory.setLegalIdCard(data.getString(AgencyInterfaceParam.LEGAL_ID_CARD)); /** ? */ agencyHistory.setConstructionArea(data.getDouble(AgencyInterfaceParam.CONSTRUCTION_AREA)); /** ? */ agencyHistory.setAgencyBedNum(data.getInteger(AgencyInterfaceParam.ORG_BED_NUM)); /** */ agencyHistory.setAdvancedDoctorNum(data.getInteger(AgencyInterfaceParam.ADVANCED_DOCTOR_NUM)); /** */ agencyHistory.setIntermediateDoctorNum(data.getInteger(AgencyInterfaceParam.INTERMEDIATE_DOCTOR_NUM)); /** ? */ agencyHistory.setPrimaryDoctorNum(data.getInteger(AgencyInterfaceParam.PRIMARY_DOCTOR_NUM)); /** ? */ agencyHistory.setNoDoctorNum(data.getInteger(AgencyInterfaceParam.NO_DOCTOR_NUM)); /** */ agencyHistory.setAdvancedNurseNum(data.getInteger(AgencyInterfaceParam.ADVANCED_NURSE_NUM)); /** */ agencyHistory.setIntermediateNurseNum(data.getInteger(AgencyInterfaceParam.INTERMEDIATE_NURSE_NUM)); /** ? */ agencyHistory.setPrimaryNurseNum(data.getInteger(AgencyInterfaceParam.PRIMARY_NURSE_NUM)); /** ? */ agencyHistory.setNoNurseNum(data.getInteger(AgencyInterfaceParam.NO_NURSE_NUM)); /** ? */ agencyHistory.setAdvancedCarerNum(data.getInteger(AgencyInterfaceParam.ADVANCED_CARER_NUM)); /** ? */ agencyHistory.setIntermediateCarerNum(data.getInteger(AgencyInterfaceParam.INTERMEDIATE_CARER_NUM)); /** ?? */ agencyHistory.setPrimaryCarerNum(data.getInteger(AgencyInterfaceParam.PRIMARY_CARER_NUM)); /** ?? */ agencyHistory.setNoCarerNum(data.getInteger(AgencyInterfaceParam.NO_CARER_NUM)); /** */ agencyHistory.setAdvancedMiscNum(data.getInteger(AgencyInterfaceParam.ADVANCED_MISC_NUM)); /** */ agencyHistory.setIntermediateMiscNum(data.getInteger(AgencyInterfaceParam.INTERMEDIATE_MISC_NUM)); /** ? */ agencyHistory.setPrimaryMiscNum(data.getInteger(AgencyInterfaceParam.PRIMARY_MISC_NUM)); /** ? */ agencyHistory.setNoMiscNum(data.getInteger(AgencyInterfaceParam.NO_MISC_NUM)); /** */ agencyHistory.setAgencyApplicat(data.getString(AgencyInterfaceParam.OPERATOR)); /** */ agencyHistory.setAgencyApplyDate(data.getDate(AgencyInterfaceParam.OPERATING_TIME)); agencyHistory.setSerialNum(BaseModel.getUUID()); agencyHistory.setValidState(IsValidEnum.NO_DELETE.getValue()); agencyHistory.setCreatedTime(new Date()); agencyHistory.setOperatedTime(new Date()); //?? if (ActionTypeEnum.CREATE.getValue().equals(data.getString(AgencyInterfaceParam.ACTION_TYPE))) { String areaCode = getAreaCode(data); String agencyCode = getAgencyCode(areaCode); //orgCode??,???? while (true) { AgencyHistoryDOExample example = new AgencyHistoryDOExample(); Criteria criteria = example.createCriteria(); criteria.andOrgCodeEqualTo(agencyCode); List<AgencyHistoryDO> list = agencyHistoryDao.selectByExample(example); if (list.isEmpty()) { //? ?code?? ???? break; } agencyCode = getAgencyCode(areaCode); } agencyHistory.setAgencyCode(agencyCode); agencyHistory.setAgencyState(AgencyStateEnum.STATE_NO_ACCEPT.getValue()); } else { agencyHistory.setAgencyState(AgencyStateEnum.STATE_ACCEPT.getValue()); } return agencyHistory; } private static String getAgencyCode(String areaCode) { StringBuffer sb = new StringBuffer(areaCode); SecureRandom random = new SecureRandom(); for (int i = 0; i < 6; i++) { sb.append(org[random.nextInt(org.length)]); } return sb.toString(); } private MqBaseModel getMqBaseModel() { MqBaseModel mqBaseModel = new MqBaseModel(); mqBaseModel.setBusinessSerialid(BaseModel.getUUID()); mqBaseModel.setTimestamp(DateFormat.getLocalDateTime()); try { mqBaseModel.setNodeIP(IPUtil.getLocalIp()); } catch (Exception e) { logger.error("?IP" + e); } mqBaseModel.setSystemCode(systemCode); return mqBaseModel; } /** ?? */ @Override public void sendOrgAcceptResult(AgencyHistoryDTO agency) { Map<String, String> map = new HashMap<>(); map.put(AgencyInterfaceParam.ORG_CODE, agency.getOrgCode()); map.put(AgencyInterfaceParam.ACCEPT_DATE, agency.getOperatedTime()); map.put(AgencyInterfaceParam.STATE, agency.getAgencyState().toString()); if (AgencyStateEnum.STATE_WITHHOLD_ACCEPT.getValue().equals(agency.getAgencyState())) { map.put(AgencyInterfaceParam.REASON, agency.getCause()); } MqBaseModel mqBaseModel = getMqBaseModel(); mqBaseModel.setMessageCode(orgAcceptResultMessageCode); mqBaseModel.setData(map); String jsonString = JSONObject.toJSONString(mqBaseModel); // messageLogService.sendMqMessageLog(0L, "0", jsonString, orgAcceptResultExchange, null); //??mq routingKey jingmen?,?queryName sendMessage(orgAcceptResultExchange, ROUTING_KEY, jsonString); } /** */ @Override public void sendOrgApproveResult(AgencyDTO agency) { Map<String, String> map = new HashMap<>(); map.put(AgencyInterfaceParam.ORG_CODE, agency.getOrgCode()); map.put(AgencyInterfaceParam.CHECK_DATE, agency.getOperatedTime()); map.put(AgencyInterfaceParam.STATE, agency.getAgencyState().toString()); if (AgencyStateEnum.STATE_NO_AUDIT.getValue().equals(agency.getAgencyState())) { //? map.put(AgencyInterfaceParam.REJECTION_REASON, agency.getRejectionReason()); } else { map.put(AgencyInterfaceParam.AGENCY_CODE, agency.getAgencyCode()); map.put(AgencyInterfaceParam.SECRET_KEY, agency.getSecretKey()); map.put(AgencyInterfaceParam.KEY_BEGIN_DATE, agency.getKeyBeginDate()); map.put(AgencyInterfaceParam.KEY_END_DATE, agency.getKeyEndDate()); } MqBaseModel mqBaseModel = getMqBaseModel(); mqBaseModel.setMessageCode(orgApproveResultMessageCode); mqBaseModel.setData(map); String jsonString = JSONObject.toJSONString(mqBaseModel); // messageLogService.sendMqMessageLog(0L, "0", jsonString, orgApproveResultExchange, null); //??mq routingKey jingmen?,?queryName sendMessage(orgApproveResultExchange, ROUTING_KEY, jsonString); } /** ? */ @Override public void sendOrgChangeResult(AgencyDTO agency) { Map<String, String> map = new HashMap<>(); map.put(AgencyInterfaceParam.ORG_CODE, agency.getOrgCode()); map.put(AgencyInterfaceParam.CHECK_DATE, agency.getOperatedTime()); map.put(AgencyInterfaceParam.STATE, agency.getAgencyState().toString()); map.put(AgencyInterfaceParam.AGENCY_CODE, agency.getAgencyCode()); if (AgencyStateEnum.STATE_NO_AUDIT.getValue().equals(agency.getAgencyState())) { map.put(AgencyInterfaceParam.REJECTION_REASON, agency.getRejectionReason()); } MqBaseModel mqBaseModel = getMqBaseModel(); mqBaseModel.setMessageCode(orgChangeResultMessageCode); mqBaseModel.setData(map); String jsonString = JSONObject.toJSONString(mqBaseModel); // messageLogService.sendMqMessageLog(0L, "0", jsonString, orgChangeResultExchange, null); //??mq routingKey jingmen?,?queryName sendMessage(orgChangeResultExchange, ROUTING_KEY, jsonString); } public void sendMessage(String exchangeName, String routingKey, String message) { try { byte[] bytes = message.getBytes(systemCharset); rabbitTemplate.convertAndSend(exchangeName, routingKey, bytes); logger.info("???MQ, exchangeName: " + exchangeName + "--message: " + message); } catch (UnsupportedEncodingException e) { logger.error("MQ??", e); throw new ThrowsException("??MQ?Stringbyte[]"); } } }