美文网首页
JOJO SPEEDO

JOJO SPEEDO

作者: e43ef8a56980 | 来源:发表于2019-08-14 17:36 被阅读0次

CLOB CONVERSION 和 发送邮件

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

@Service("reportTService")
@Transactional
public class ReportTServiceImpl implements ReportTService {
    
    static final Logger logger = LoggerFactory.getLogger(ReportTServiceImpl.class);
            
    private static final String USER_NAME = "userName";//邮件模板中的{收件人}占位笄1�7
    
    @Autowired
    private ReportTDao reportTDao;
    
    @Autowired
    private RestTemplate restTemplate;
    
    
    @Value("${email.name.new}")
    private String emailName;
    
    @Value("${email.appId}")
    private String emailAppId;
    
    @Value("${email.registerCode}")
    private String registerCode;
    
    @Value("${email.address}")
    private String emailAddress;
    
    @Value("${exam.pc.card.address.safe.v2}")
    private String pcAddress;
    
    @Autowired
    private IOBSFileUtil iobsFileUtil;
    
    
    
    @Override
    public void sendReportMail(String attachName,byte[] zipBytes,List<ReportMailT> toMailList,List<ReportMailT> ccMailList,
            List<InnerEmailMessage> sendList) {
        
        //存储变量
        Map<String,String> dataMap = new HashMap<>();
        dataMap.put(TemplateConstant.DATA_EXAM_URL,pcAddress);
//      dataMap.put(TemplateConstant.DATA_EXAM_TIME, DateUtil.format(endTime, "yyyy/MM/dd  HH:mm:ss"));
        dataMap.put(USER_NAME, getMailReceiverStr(toMailList));
        
        //邮件模板,测评任务通知模板,系统模杄1�7
        AAATemplateTQuery templateTQuery = new AAATemplateTQuery();
        templateTQuery.setTempType(Integer.parseInt(TemplateConstant.REPORT_SEND));
        templateTQuery.setSelFlag(BaseFlagConstant.TRUE_NUM);
        AAATemplateT templateT = AAATemplateTService.getAAATemplateTByQuery(templateTQuery);
                
        IOBSFileBean bean = new IOBSFileBean();
        long ran = System.currentTimeMillis();
         bean.setFileName(ran + "report.zip");
         bean.setIns(zipBytes);
         bean.setKey(UUIDHexGenerator.generate());
         bean.setLength(zipBytes.length);
         
         logger.info("上传bean名字:{},key:{}", bean.getFileName(),bean.getKey());
        
         // 调用IOBS文件上传服务
         IOBSUploadResult iobsUploadResult = iobsFileUtil.uploadPubFile(bean);
         String innerUrl = iobsUploadResult.getInnerUrl();
         String outerUrl = iobsUploadResult.getOuterUrl();
         
         EmailMessageAttachment attach = new EmailMessageAttachment();
         attach.setUrlLocation(innerUrl);
         attach.setName(".zip");
         attach.setDescription(attachName);
         
         this.createTempMail(dataMap, toMailList,ccMailList, templateT, sendList, attach);
         try {
            AAASendMessageService.AAASendInnerEmailMessages(sendList);
        } catch (HippoException e) {
            // TODO Auto-generated catch block
            logger.error("unExpect error :" , e);
        }
    }
    
    
    
    @Override
    public void sendMailForOneReport(String attachName, byte[] content, List<ReportMailT> toMailList,
            List<ReportMailT> ccMailList, List<InnerEmailMessage> sendList) {
        //存储变量
                Map<String,String> dataMap = new HashMap<>();
                dataMap.put(TemplateConstant.DATA_EXAM_URL,pcAddress);
//              dataMap.put(TemplateConstant.DATA_EXAM_TIME, DateUtil.format(endTime, "yyyy/MM/dd  HH:mm:ss"));
                dataMap.put(USER_NAME, getMailReceiverStr(toMailList));
                
                //邮件模板,测评任务通知模板,系统模杄1�7
                AAATemplateTQuery templateTQuery = new AAATemplateTQuery();
                templateTQuery.setTempType(Integer.parseInt(TemplateConstant.REPORT_SEND));
                templateTQuery.setSelFlag(BaseFlagConstant.TRUE_NUM);
                AAATemplateT templateT = AAATemplateTService.getAAATemplateTByQuery(templateTQuery);
                        
                IOBSFileBean bean = new IOBSFileBean();
                 bean.setFileName(attachName);
                 bean.setIns(content);
                 bean.setKey(UUIDHexGenerator.generate());
                 bean.setLength(content.length);
                 
                 logger.info("上传bean名字:{},key:{}", bean.getFileName(), bean.getKey());
                
                 // 调用IOBS文件上传服务
                 IOBSUploadResult iobsUploadResult = iobsFileUtil.uploadPubFile(bean);
                 String innerUrl = iobsUploadResult.getInnerUrl();
                 String outerUrl = iobsUploadResult.getOuterUrl();
                 
                 EmailMessageAttachment attach = new EmailMessageAttachment();
                 attach.setUrlLocation(innerUrl);
                 attach.setName(".pdf");
                 attach.setDescription(attachName);
                 
                 this.createTempMail(dataMap, toMailList,ccMailList, templateT, sendList, attach);
                 try {
                    AAASendMessageService.AAASendInnerEmailMessages(sendList);
                } catch (HippoException e) {
                    // TODO Auto-generated catch block
                    logger.error("unExpect error :" , e);
                }
        
    }

    
    private String filldata(String context, Map<String,String> dataMap,String placeholderData) {
        
        context = context.replaceAll("\\{" + placeholderData + "\\}", dataMap.get(placeholderData));
        return context;
    }
    
    
    
    private void createTempMail(Map<String,String> dataMap,List<ReportMailT> toMailList,List<ReportMailT> ccMailList,
            AAATemplateT template,List<InnerEmailMessage> sendList,EmailMessageAttachment attach){
        //组装邮件
        System.setProperty("mail.mime.charset","UTF-8");
//      dataMap.put(TemplateConstant.DATA_USER_NAME, reportMail.getUserName());
        InnerEmailMessage email = new InnerEmailMessage();
        Map<String, String> parameters = new HashMap<String, String>();
        email.setSubject(template.getTheme());
        parameters.put("emailTitle", template.getTheme());
        parameters.put("content", filldata(template.getContext(),dataMap,USER_NAME));
        email.setParameters(parameters);
        email.setRegisterCode(registerCode);
        EmailAddressVO addressVO = new EmailAddressVO();
        addressVO.setName(emailName);
        addressVO.setAddress(emailAddress);
        email.setForm(addressVO);
        email.setTenantid(ExamConstant.TENANTID);
        email.setAppId(emailAppId);
        
        //收件人列衄1�7
        List<EmailAddressVO> toList = new ArrayList<EmailAddressVO>();
        for(ReportMailT toMail : toMailList){
            EmailAddressVO to = new EmailAddressVO();
            to.setAddress(toMail.getEmailAddress());
            to.setName(toMail.getUserName());
            toList.add(to);
        }
        email.setToList(toList);
        
        //抄�1�7�人列表
        List<EmailAddressVO> ccList = new ArrayList<EmailAddressVO>();
        for(ReportMailT ccMail : ccMailList){
            EmailAddressVO cc = new EmailAddressVO();
            cc.setAddress(ccMail.getEmailAddress());
            cc.setName(ccMail.getUserName());
            ccList.add(cc);
        }
        
        email.setCcList(ccList);
        
        //附件
//        EmailMessageAttachment attach = new EmailMessageAttachment();
//        attach.setUrlLocation(urlLocation);
        List<EmailMessageAttachment> attachList = new ArrayList<EmailMessageAttachment>();
        attachList.add(attach);
        email.setAttachmentList(attachList);
        sendList.add(email);
    }
    
    

    @Override
    public List<PersonReportT> getReportLists(List<String> examIds) {
        List<PersonReportT> reportList = new ArrayList<>();
        // 20180904 对超过1000条的数据提供支持,分批查询um账号
        if(examIds != null && examIds.size() > 0){
            List<List<String>> idsList = ListUtils.averageAssign(examIds, (int) Math.ceil((double) examIds.size() / 900));
            for (List<String> l : idsList) {
                List<PersonReportT> answerUsersTemp = reportTDao.getReportLists(l);
                reportList.addAll(answerUsersTemp);
            }
        }
        if (CollectionUtils.isEmpty(reportList)) {
            reportList = new ArrayList<PersonReportT>();
        }
        return reportList;
    }
    
    @SuppressWarnings({ "rawtypes","unchecked"})
    private List<Map> convertClobDataToString(List<Map> paramList) throws Exception{
        if(paramList!=null){
            for(Map map:paramList){
                map.put("ITEMRESULT", ClobToString((Clob) map.get("ITEMRESULT")));
            }
        }
        return paramList;
    }
    
     // 将字Clob转成String类型  
    private String ClobToString(Clob sc) throws SQLException, IOException {
        Reader is = null;
        BufferedReader br = null;
        try{
            String reString = "";
            is = sc.getCharacterStream();// 得到浄1�7
            br = new BufferedReader(is);
            String s = br.readLine();
            StringBuffer sb = new StringBuffer();
            while (s != null) {// 执行循环将字符串全部取出付�1�7�给StringBuffer由StringBuffer转成STRING
                sb.append(s);
                s = br.readLine();
            }
            reString = sb.toString();
            return reString;
        }catch(Exception e){
//          logger.error("ClobToString has exception" ,e);
            throw e;
        }finally {
            if(br != null){
                br.close();
            }
            if(is != null){
                is.close();
            }
        }
    }
    
}

package jojo.speedo.common.auditlog;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aopalliance.aop.Advice;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.jojo.eargle.core.exception.eargleException;
import com.jojo.eargle.core.response.ResponseState;
import com.jojo.eargle.core.response.ResponseVO;

import jojo.speedo.common.util.IpAddressUtil;
import jojo.speedo.common.util.LocalIpAddressUtils;


public class AuditLogControllerMethodAdvice extends StaticMethodMatcherPointcutAdvisor
        implements InitializingBean, MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {
    private static final long serialVersionUID = -6960762949903366228L;
    private static final String OPERATION_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss:SSS";
    private final Logger logger = LoggerFactory.getLogger(AuditLogControllerMethodAdvice.class);
    private final Logger auditLogger = LoggerFactory.getLogger("auditLogger"); // 日志埋点约定的logger
    private OperationUserInfoProvider operationUserInfoProvider;

    
    protected String companyCode = "PA011";

    
    protected String appId;

    
    protected String serverIp;

    public void setCompanyCode(String companyCode) {
        this.companyCode = companyCode;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public void setOperationUserInfoProvider(OperationUserInfoProvider operationUserInfoProvider) {
        this.operationUserInfoProvider = operationUserInfoProvider;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (null == operationUserInfoProvider) {
            throw new BeanInitializationException("AuditLoggerWebInterceptor的配置不可缺少operationUserInfoProvider参数");
        }
        this.serverIp = LocalIpAddressUtils.getIp();
        logger.debug("识别当前服务器IP:{}", this.serverIp);
    }

    @Override
    public boolean matches(Method method, Class<?> targetClass) {
        AuditLogRequired auditLogRequired = AnnotationUtils.findAnnotation(method, AuditLogRequired.class);
        return null != auditLogRequired;
    }

    @Override
    public ClassFilter getClassFilter() {
        return new ClassFilter() {
            @Override
            public boolean matches(Class<?> clazz) {
                return AnnotationUtils.isAnnotationDeclaredLocally(Controller.class, clazz);
            }
        };
    }

    @Override
    public void setAdvice(Advice advice) {
        throw new UnsupportedOperationException("不允许修改或设置advice");
    }

    @Override
    public Advice getAdvice() {
        return this;
    }

    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        HttpServletRequest request = getCurrentRequest();
        if (null == request) {
            return;
        }
        AuditLogRequired auditAnnotation = AnnotationUtils.getAnnotation(method, AuditLogRequired.class);
        if (null != auditAnnotation) {
            String funcName = auditAnnotation.funcName();
            OperationType oprType = auditAnnotation.oprType();
            if (null == funcName || 0 == funcName.length()) {
                throw new IllegalArgumentException("代码未按规范开发,请检查并确保AuditLogger注解中的funcName参数不为空");
            }
            if (null == oprType) {
                throw new IllegalArgumentException("代码未按规范开发,请检查并确保AuditLogger注解中的oprType参数不为null");
            }

            String clientIp = IpAddressUtil.getIpAdrress(request);
            if (null == clientIp || 0 == clientIp.length()) {
                clientIp = "0.0.0.0";
            }

//              String requestUrl = ServletUriComponentsBuilder.fromRequest(request).build().toUriString();
//              logger.debug("requestUrl: {}", requestUrl);
//              logger.debug("requestUrl[2]: {}", request.getRequestURL().toString());
//              logger.debug("requestUrl[3]: {}", request.getRequestURI());

            String requestUrl = request.getRequestURI();

            AuditLoggerContext.setNeedAuditLogging(true);
            AuditLoggerData auditLoggerData = AuditLoggerContext.getOrCreateAuditLoggerData();
            auditLoggerData.setRequestType(funcName);
            auditLoggerData.setOperationType(oprType.getTypeCode());

            auditLoggerData.setOperationTime(DateFormatUtils.format(new Date(), OPERATION_TIME_FORMAT));
            auditLoggerData.setCompanyCode(companyCode);
            auditLoggerData.setAppId(appId);
            auditLoggerData.setServerIp(serverIp);
            auditLoggerData.setSrcIp(clientIp);
            auditLoggerData.setRequestUrl(requestUrl);

            if (OperationType.login != auditAnnotation.oprType()) {
                fillOperationUserInfo(request, auditLoggerData);
            }
        }
    }

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        if (!AuditLoggerContext.isNeedAuditLogging()) {
            return;
        }
        HttpServletRequest request = getCurrentRequest();
        try {
            if (null != returnValue && returnValue instanceof ResponseVO) {
                ResponseVO respVo = (ResponseVO) returnValue;
                if (!ResponseState.SUCCESS.getCode().equals(respVo.getResponseCode())) {
                    AuditLoggerContext.setOperationResult(OperationResult.FAILED);
                    AuditLoggerContext.setFailReason(respVo.getResponseCode() + "-" + respVo.getResponseMsg());
                }
            }

            AuditLoggerData auditData = AuditLoggerContext.getOrCreateAuditLoggerData();
            if (!AuditLoggerContext.isOprUserFilled()) {
                fillOperationUserInfo(request, auditData);
            }
            
            if(null != auditData.getOperationUserId() && auditData.getOperationUserId().length() > 0) {
                auditLogger.info("{}", AuditLoggerDataWrapper.wrap(auditData));
            }
        } catch (Throwable e) {
            logger.warn("Failed to write audit log due to exception: {}", e.getMessage(), e);
        } finally {
            AuditLoggerContext.resetContext();
        }
    }

    private void fillOperationUserInfo(HttpServletRequest request, AuditLoggerData auditData) {
        OperationUser operationUser = operationUserInfoProvider.getOperationUser(request);
        if (null != operationUser) {
            if (null != operationUser.getOperationUserType()) {
                auditData.setOperationUserType(operationUser.getOperationUserType().getTypeCode());
            }
            auditData.setOperationUserId(operationUser.getOperationUserId());
            if (null != operationUser.getOperationUser() && operationUser.getOperationUser().length() > 0) {
                auditData.setOperationUser(operationUser.getOperationUser());
            } else {
                auditData.setOperationUser(operationUser.getOperationUserId());
            }
            AuditLoggerContext.setisOprUserFilledFlag(true);
        }
    }

    // ThrowsAdvice
    public void afterThrowing(Method method, Object[] args, Object target, Exception ex) {
        if (!AuditLoggerContext.isNeedAuditLogging()) {
            return;
        }
        HttpServletRequest request = getCurrentRequest();
        try {
            String exceptionMsg;
            if (ex instanceof eargleException) {
                eargleException hiEx = (eargleException) ex;
                exceptionMsg = hiEx.getResponseCode() + "-" + hiEx.getMessage();
            } else {
                exceptionMsg = ex.getMessage();
            }

            if (null == exceptionMsg) {
                exceptionMsg = ex.getClass().getSimpleName();
            }
            AuditLoggerContext.setOperationResult(OperationResult.FAILED);
            AuditLoggerContext.setFailReason(exceptionMsg);

            AuditLoggerData auditData = AuditLoggerContext.getOrCreateAuditLoggerData();
            if (!AuditLoggerContext.isOprUserFilled()) {
                fillOperationUserInfo(request, auditData);
            }

            auditLogger.info("{}", AuditLoggerDataWrapper.wrap(auditData));
        } catch (

        Throwable e) {
            logger.warn("Failed to write audit log due to exception: {}", e.getMessage(), e);
        } finally {
            AuditLoggerContext.resetContext();
        }
    }

    // may be null
    private HttpServletRequest getCurrentRequest() {
        HttpServletRequest request = null;
        RequestAttributes reqAttrs = RequestContextHolder.getRequestAttributes();
        if (null != reqAttrs && reqAttrs instanceof ServletRequestAttributes) {
            request = ((ServletRequestAttributes) reqAttrs).getRequest();
        }
        return request;
    }

}
package jojo.speedo.common.auditlog;


public abstract class AuditLogCxtHelperForLogin {

    
    public static void setOperationUserType(OperationUserType userType) {
        if (null != userType) {
            AuditLoggerContext.getOrCreateAuditLoggerData().setOperationUserType(userType.getTypeCode());
        }
    }

    
    public static void setOperationUserId(String operationUserId) {
        if (null != operationUserId && operationUserId.length() > 0) {
            AuditLoggerContext.getOrCreateAuditLoggerData().setOperationUserId(operationUserId);
        }
    }

    
    public static void setOperationUser(String operationUser) {
        if (null != operationUser && operationUser.length() > 0) {
            AuditLoggerContext.getOrCreateAuditLoggerData().setOperationUser(operationUser);
        }
    }

}
package jojo.speedo.common.auditlog;


public abstract class AuditLoggerContext {
    private static final int FAIL_REASON_MAX_LENGTH = 200;
    // 当前请求是否需要进行日志埋点处理
    private static final ThreadLocal<Boolean> NEED_AUDIT_LOGGING_FLAG = new ThreadLocal<>();
    // 当前请求的操作用户信息是否已填充完毕
    private static final ThreadLocal<Boolean> OPR_USER_FILLED_FLAG = new ThreadLocal<>();
    // 日志埋点内容
    private static final ThreadLocal<AuditLoggerData> CTX = new ThreadLocal<>();

    
    public static void setOperationObject(String operationObject) {
        setOperationObject(operationObject, false);
    }

    
    public static void setOperationObject(String operationObject, boolean isSensitivityData) {
        if (null != operationObject && operationObject.length() > 0 && isSensitivityData) {
            operationObject = String.valueOf(operationObject.hashCode());
        }

        getOrCreateAuditLoggerData().setOperationObject(operationObject);
    }

    
    public static void setRecordCounts(int recordCounts) {
        if (recordCounts < 0) {
            recordCounts = 0;
        }
        getOrCreateAuditLoggerData().setRecordCounts(recordCounts);
    }

    
    public static void setTargetUserId(String userId) {
        getOrCreateAuditLoggerData().setUserId(userId);
    }

    
    public static void setOperationResult(OperationResult operationResult) {
        if (null == operationResult) {
            throw new IllegalArgumentException("setOperationResult入参不允许为null");
        }
        getOrCreateAuditLoggerData().setOperationResult(operationResult.getResultDesc());
    }

    
    public static void setFailReason(String failReason) {
        if (null != failReason && failReason.length() > FAIL_REASON_MAX_LENGTH) {
            failReason = failReason.substring(0, FAIL_REASON_MAX_LENGTH);
        }
        getOrCreateAuditLoggerData().setFailReason(failReason);
    }

    // 该方法具体接口功能代码范围内不可见。
    protected static void resetContext() {
        NEED_AUDIT_LOGGING_FLAG.remove();
        OPR_USER_FILLED_FLAG.remove();
        CTX.remove();
    }

    // 标识当前请求是否涉及日志埋点
    protected static void setNeedAuditLogging(boolean needAuditLogging) {
        NEED_AUDIT_LOGGING_FLAG.set(Boolean.valueOf(needAuditLogging));
    }

    // 标识当前请求的操作用户信息是否填充完毕
    protected static void setisOprUserFilledFlag(boolean oprUserFilledFlag) {
        OPR_USER_FILLED_FLAG.set(Boolean.valueOf(oprUserFilledFlag));
    }

    // 该方法具体接口功能代码范围内不可见。
    protected static AuditLoggerData getOrCreateAuditLoggerData() {
        AuditLoggerData data = CTX.get();
        if (null == data) {
            data = new AuditLoggerData();
            CTX.set(data);
        }
        return data;
    }

    // 判断当前请求是否涉及日志埋点处理
    protected static boolean isNeedAuditLogging() {
        Boolean b = NEED_AUDIT_LOGGING_FLAG.get();
        return null != b && b.booleanValue();
    }

    // 判断当前请求的操作用户信息是否已填充完毕
    protected static boolean isOprUserFilled() {
        Boolean b = OPR_USER_FILLED_FLAG.get();
        return (null != b && b.booleanValue());
    }

}

package jojo.speedo.common.auditlog;

import com.fasterxml.jackson.annotation.JsonProperty;


public class AuditLoggerData {

    
    private @JsonProperty("company_code") String companyCode;

    
    private @JsonProperty("appId") String appId;

    
    private @JsonProperty("operation_time") String operationTime;

    
    private @JsonProperty("operation_userType") String operationUserType;

    
    private @JsonProperty("operation_userID") String operationUserId;

    
    private @JsonProperty("operation_user") String operationUser;

    
    private @JsonProperty("src_ip") String srcIp;

    
    private @JsonProperty("server_ip") String serverIp;

    
    private @JsonProperty("operation_type") String operationType;

    
    private @JsonProperty("operation_object") String operationObject;

    
    private @JsonProperty("operation_result") String operationResult = "成功";
    
    private @JsonProperty("record_counts") int recordCounts = 0;

    
    private @JsonProperty("request_type") String requestType;
    
    private @JsonProperty("request_url") String requestUrl;

    
    private @JsonProperty("failReason") String failReason;

    
    private @JsonProperty("userid") String userId;

    public String getCompanyCode() {
        return companyCode;
    }

    public void setCompanyCode(String companyCode) {
        this.companyCode = companyCode;
    }

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public String getOperationTime() {
        return operationTime;
    }

    public void setOperationTime(String operationTime) {
        this.operationTime = operationTime;
    }

    public String getOperationUserType() {
        return operationUserType;
    }

    public void setOperationUserType(String operationUserType) {
        this.operationUserType = operationUserType;
    }

    public String getOperationUserId() {
        return operationUserId;
    }

    public void setOperationUserId(String operationUserId) {
        this.operationUserId = operationUserId;
    }

    public String getOperationUser() {
        return operationUser;
    }

    public void setOperationUser(String operationUser) {
        this.operationUser = operationUser;
    }

    public String getSrcIp() {
        return srcIp;
    }

    public void setSrcIp(String srcIp) {
        this.srcIp = srcIp;
    }

    public String getServerIp() {
        return serverIp;
    }

    public void setServerIp(String serverIp) {
        this.serverIp = serverIp;
    }

    public String getOperationType() {
        return operationType;
    }

    public void setOperationType(String operationType) {
        this.operationType = operationType;
    }

    public String getOperationObject() {
        return operationObject;
    }

    public void setOperationObject(String operationObject) {
        this.operationObject = operationObject;
    }

    public String getOperationResult() {
        return operationResult;
    }

    public void setOperationResult(String operationResult) {
        this.operationResult = operationResult;
    }

    public int getRecordCounts() {
        return recordCounts;
    }

    public void setRecordCounts(int recordCounts) {
        this.recordCounts = recordCounts;
    }

    public String getRequestType() {
        return requestType;
    }

    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    public String getRequestUrl() {
        return requestUrl;
    }

    public void setRequestUrl(String requestUrl) {
        this.requestUrl = requestUrl;
    }

    public String getFailReason() {
        return failReason;
    }

    public void setFailReason(String failReason) {
        this.failReason = failReason;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

}
package jojo.speedo.common.auditlog;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;


public class AuditLoggerDataWrapper {
    static final Logger LOGGER = LoggerFactory.getLogger(AuditLoggerDataWrapper.class);
    private static final ObjectMapper JSON_MAPPER;

    static {
        JSON_MAPPER = new ObjectMapper();
        JSON_MAPPER.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
        JSON_MAPPER.configure(JsonGenerator.Feature.QUOTE_NON_NUMERIC_NUMBERS, true);
        JSON_MAPPER.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
                    throws IOException, JsonProcessingException {
                jgen.writeString("null");
            }
        });
    }

    private AuditLoggerData obj;

    private AuditLoggerDataWrapper(AuditLoggerData obj) {
        this.obj = obj;
    }

    public static AuditLoggerDataWrapper wrap(AuditLoggerData obj) {
        if (null == obj) {
            return null;
        }
        return new AuditLoggerDataWrapper(obj);
    }

    @Override
    public String toString() {
        try {
            return JSON_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            LOGGER.warn("Failed to serialize AuditLoggerData object to json: {}", e.getMessage(), e);
        }
        return "";
    }

}
package jojo.speedo.common.auditlog;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;


@Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface AuditLogRequired {

    
    String funcName();

    
    OperationType oprType();

}

package jojo.speedo.common.auditlog;


public enum OperationResult {

    SUCCESS("SUCCESS", "成功"),

    FAILED("FAILED", "失败"),

    ;

    private String resultCode;
    private String resultDesc;

    private OperationResult(String resultCode, String resultDesc) {
        this.resultCode = resultCode;
        this.resultDesc = resultDesc;
    }

    public String getResultCode() {
        return resultCode;
    }

    public String getResultDesc() {
        return resultDesc;
    }

}

package jojo.speedo.common.auditlog;


public enum OperationType {

    login("login", "登录"),

    logout("logout", "登出"),

    add("add", "新增"),

    delete("delete", "删除"),

    modify("modify", "修改"),

    query("query", "查询"),

    upload("upload", "上传"),

    download("download", "下载"),

    print("print", "打印"),
    
    sendmail("sendmail", "发送邮件"),

    ;

    private String typeCode;
    private String typeDesc;

    private OperationType(String typeCode, String typeDesc) {
        this.typeCode = typeCode;
        this.typeDesc = typeDesc;
    }

    public String getTypeCode() {
        return typeCode;
    }

    public String getTypeDesc() {
        return typeDesc;
    }

}
package jojo.speedo.common.auditlog;


public class OperationUser {
    private OperationUserType operationUserType;
    private String operationUserId;
    private String operationUser;

    public OperationUserType getOperationUserType() {
        return operationUserType;
    }

    
    public void setOperationUserType(OperationUserType operationUserType) {
        this.operationUserType = operationUserType;
    }

    public String getOperationUserId() {
        return operationUserId;
    }

    
    public void setOperationUserId(String operationUserId) {
        this.operationUserId = operationUserId;
    }

    public String getOperationUser() {
        return operationUser;
    }

    
    public void setOperationUser(String operationUser) {
        this.operationUser = operationUser;
    }

}
package jojo.speedo.common.auditlog;

import javax.servlet.http.HttpServletRequest;


public interface OperationUserInfoProvider {

    
    OperationUser getOperationUser(HttpServletRequest request);

}
package jojo.speedo.common.auditlog;


public enum OperationUserType {

    um("um", "UM账号用户"),

    ad("ad", "域账号用户"),
    
    mobile("mobile", "候选人手机号"),

    partner("partner", "合作方ID"),

    ;

    private String typeCode;
    private String typeDesc;

    private OperationUserType(String typeCode, String typeDesc) {
        this.typeCode = typeCode;
        this.typeDesc = typeDesc;
    }

    public String getTypeCode() {
        return typeCode;
    }

    public String getTypeDesc() {
        return typeDesc;
    }

}
package jojo.speedo.common.httpclient;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

public class HttpclientBuilder {

    private HttpClientConnectionManager connectionManager;

    private SSLConnectionSocketFactory sslSocketFactory;

    private RequestConfig defaultRequestConfig;

    public CloseableHttpClient build() {
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setConnectionManager(connectionManager);
        builder.setSSLSocketFactory(sslSocketFactory);
        builder.setDefaultRequestConfig(defaultRequestConfig);
        return builder.build();
    }

    public HttpClientConnectionManager getConnectionManager() {
        return connectionManager;
    }

    public void setConnectionManager(HttpClientConnectionManager connectionManager) {
        this.connectionManager = connectionManager;
    }

    public SSLConnectionSocketFactory getSslSocketFactory() {
        return sslSocketFactory;
    }

    public void setSslSocketFactory(SSLConnectionSocketFactory sslSocketFactory) {
        this.sslSocketFactory = sslSocketFactory;
    }

    public RequestConfig getDefaultRequestConfig() {
        return defaultRequestConfig;
    }

    public void setDefaultRequestConfig(RequestConfig defaultRequestConfig) {
        this.defaultRequestConfig = defaultRequestConfig;
    }
}

package jojo.speedo.common.httpclient;


import java.net.InetAddress;
import java.util.Collection;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;

public class HttpRequestConfigBuilder {
    private boolean expectContinueEnabled;
    private HttpHost proxy;
    private InetAddress localAddress;
    private boolean staleConnectionCheckEnabled;
    private String cookieSpec;
    private boolean redirectsEnabled;
    private boolean relativeRedirectsAllowed;
    private boolean circularRedirectsAllowed;
    private int maxRedirects;
    private boolean authenticationEnabled;
    private Collection<String> targetPreferredAuthSchemes;
    private Collection<String> proxyPreferredAuthSchemes;
    private int connectionRequestTimeout;
    private int connectTimeout;
    private int socketTimeout;

    public boolean isExpectContinueEnabled() {
        return expectContinueEnabled;
    }

    public void setExpectContinueEnabled(boolean expectContinueEnabled) {
        this.expectContinueEnabled = expectContinueEnabled;
    }

    public HttpHost getProxy() {
        return proxy;
    }

    public void setProxy(HttpHost proxy) {
        this.proxy = proxy;
    }

    public InetAddress getLocalAddress() {
        return localAddress;
    }

    public void setLocalAddress(InetAddress localAddress) {
        this.localAddress = localAddress;
    }

    public boolean isStaleConnectionCheckEnabled() {
        return staleConnectionCheckEnabled;
    }

    public void setStaleConnectionCheckEnabled(boolean staleConnectionCheckEnabled) {
        this.staleConnectionCheckEnabled = staleConnectionCheckEnabled;
    }

    public String getCookieSpec() {
        return cookieSpec;
    }

    public void setCookieSpec(String cookieSpec) {
        this.cookieSpec = cookieSpec;
    }

    public boolean isRedirectsEnabled() {
        return redirectsEnabled;
    }

    public void setRedirectsEnabled(boolean redirectsEnabled) {
        this.redirectsEnabled = redirectsEnabled;
    }

    public boolean isRelativeRedirectsAllowed() {
        return relativeRedirectsAllowed;
    }

    public void setRelativeRedirectsAllowed(boolean relativeRedirectsAllowed) {
        this.relativeRedirectsAllowed = relativeRedirectsAllowed;
    }

    public boolean isCircularRedirectsAllowed() {
        return circularRedirectsAllowed;
    }

    public void setCircularRedirectsAllowed(boolean circularRedirectsAllowed) {
        this.circularRedirectsAllowed = circularRedirectsAllowed;
    }

    public int getMaxRedirects() {
        return maxRedirects;
    }

    public void setMaxRedirects(int maxRedirects) {
        this.maxRedirects = maxRedirects;
    }

    public boolean isAuthenticationEnabled() {
        return authenticationEnabled;
    }

    public void setAuthenticationEnabled(boolean authenticationEnabled) {
        this.authenticationEnabled = authenticationEnabled;
    }

    public Collection<String> getTargetPreferredAuthSchemes() {
        return targetPreferredAuthSchemes;
    }

    public void setTargetPreferredAuthSchemes(Collection<String> targetPreferredAuthSchemes) {
        this.targetPreferredAuthSchemes = targetPreferredAuthSchemes;
    }

    public Collection<String> getProxyPreferredAuthSchemes() {
        return proxyPreferredAuthSchemes;
    }

    public void setProxyPreferredAuthSchemes(Collection<String> proxyPreferredAuthSchemes) {
        this.proxyPreferredAuthSchemes = proxyPreferredAuthSchemes;
    }

    public int getConnectionRequestTimeout() {
        return connectionRequestTimeout;
    }

    public void setConnectionRequestTimeout(int connectionRequestTimeout) {
        this.connectionRequestTimeout = connectionRequestTimeout;
    }

    public int getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(int connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public int getSocketTimeout() {
        return socketTimeout;
    }

    public void setSocketTimeout(int socketTimeout) {
        this.socketTimeout = socketTimeout;
    }

    public RequestConfig build() {
        RequestConfig.Builder builder = RequestConfig.custom();
        builder.setExpectContinueEnabled(expectContinueEnabled);
        builder.setProxy(proxy);
        builder.setLocalAddress(localAddress);
        builder.setStaleConnectionCheckEnabled(staleConnectionCheckEnabled);
        builder.setCookieSpec(cookieSpec);
        builder.setRedirectsEnabled(redirectsEnabled);
        builder.setRelativeRedirectsAllowed(relativeRedirectsAllowed);
        builder.setCircularRedirectsAllowed(circularRedirectsAllowed);
        builder.setMaxRedirects(maxRedirects);
        builder.setAuthenticationEnabled(authenticationEnabled);
        builder.setTargetPreferredAuthSchemes(targetPreferredAuthSchemes);
        builder.setProxyPreferredAuthSchemes(proxyPreferredAuthSchemes);
        builder.setConnectionRequestTimeout(connectionRequestTimeout);
        builder.setConnectTimeout(connectTimeout);
        builder.setSocketTimeout(socketTimeout);
        return builder.build();
    }
}

package jojo.speedo.common.httpclient;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;

public class InSecureSSLConnectionSocketFactoryBuilder {

    public static final SSLConnectionSocketFactory build() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

        SSLContext sslContext = new org.apache.http.ssl.SSLContextBuilder().loadTrustMaterial(null, new org.apache.http.ssl.TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        return sslSocketFactory;
    }
}
package jojo.speedo.common.httpclient;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;

public class SocketFactoryRegistryBuilder {

    public static Registry<ConnectionSocketFactory> build(SSLConnectionSocketFactory sslSocketFactory){
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory)
                .build();
        return socketFactoryRegistry;
    }
}

相关文章

网友评论

      本文标题:JOJO SPEEDO

      本文链接:https://www.haomeiwen.com/subject/glsnjctx.html