工具类

来源:互联网 发布:微信有淘宝接口 编辑:程序博客网 时间:2024/05/16 12:07
package com.lvmama.comm.utils;

import com.lvmama.comm.pet.po.user.UserUser;
import com.lvmama.comm.user.vo.Constant;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.lvmama.comm.user.utils.StringUtil;
import com.lvmama.comm.user.utils.MD5;
import com.lvmama.comm.user.utils.UUIDGenerator;
import com.lvmama.comm.user.utils.HttpsUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Random;

public final class UserUserUtil {
    private static final Log LOG = LogFactory.getLog(UserUserUtil.class);
    /**
     * 指数
     */
    private static final int INDEX = 10;
    /**
     * 明文密码前后截短长度
     */
    private static final int TRUNK_LEN = 8;
    /**
     * 静默注册时USER后面的数字的长度
     */
    private static final int USERNAME_LENGTH = 8;
    /**
     * 系统生成默认的用户
     * @return 默认用户
     */
    public static synchronized UserUser genDefaultUser() {
        UserUser user = getNewUser();

        user.setUserName(“lv” + new Random().nextInt((int) Math.pow(INDEX, USERNAME_LENGTH)));
        resetPassword(user);
        return user;
    }

    /**
     * 直接使用手机号生成的默认用户(用户名是lv+手机号、密码是手机号后6位)
     * @param mobile 手机号
     * @return 默认用户
     */
    public static synchronized UserUser genDefaultUserByMobile(final String mobile) {
        UserUser user = getNewUser();
        user.setMobileNumber(mobile);
        //user.setUserName(“lv” + mobile);
        user.setUserName(“lv”+user.getMobileNumber().substring(0,user.getMobileNumber().length()-4)+getRandomStr(4));
        resetPassword(user);
        return user;
    }

    /**
     * 校验码生成器
     * @return 校验码
     */
    public static synchronized String authenticationCodeGenerator() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < Constant.AUTHENTICATION_CODE_LENGTH; i++) {
            sb.append(Constant.AUTHENTICATION_CODE_ELEMENT.charAt(
                    random.nextInt(Constant.AUTHENTICATION_CODE_ELEMENT.length())));
        }
        return sb.toString();
    }

    /**
     * 明文密码生成器
     * @return 明文密码
     */
    public static synchronized String passwordGenerator() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < Constant.PASSWORD_LENGTH; i++) {
            sb.append(Constant.PASSWORD_ELEMENT.charAt(random.nextInt(Constant.PASSWORD_ELEMENT.length())));
        }
        return sb.toString();
    }

    /**
     * 密码加密
     * @param password 明文密码
     * @return  加密后的密码
     * @throws NoSuchAlgorithmException NoSuchAlgorithmException
     */
    public static synchronized String encodePassword(final String password) throws NoSuchAlgorithmException {
        String password1 = “”;
        if (StringUtils.isEmpty(password)) {
            password1 = passwordGenerator();
        } else {
            password1 = password;
        }
        password1 = new MD5().code(password1);
        return password1.substring(TRUNK_LEN, password1.length() - TRUNK_LEN);
    }

    /**
     * 重置密码
     * @param user 用户
     * @return 用户
     */
    public static synchronized UserUser resetPassword(final UserUser user) {
//        if (null == user.getMobileNumber()) {
            user.setRealPass(passwordGenerator());
//        } else {
//            user.setRealPass(user.getMobileNumber().substring(user.getMobileNumber().length()-6, user.getMobileNumber().length()));
//        }
        try {
            user.setUserPassword(encodePassword(user.getRealPass()));
        } catch (NoSuchAlgorithmException nsae) {
            LOG.error(nsae);
        }
        return user;
    }
    
    /**
     * 获得新用户对象
     * @return
     */
    private static UserUser getNewUser() {
        UserUser user = new UserUser();
        String userNo = new UUIDGenerator().generate().toString();

        user.setUserNo(userNo);
        user.setGroupId(Constant.USER_CHANNEL.GP_FRONT.name());
        user.setNickName(user.getUserName());
        user.setIsEmailChecked(“N”);
        user.setIsMobileChecked(“N”);
        user.setIsLocked(“N”);
        user.setIsValid(“Y”);
        user.setCreatedDate(new Date());
        user.setPoint(0L);
        //user.setLastLoginDate(new Date());
        user.setUpdatedDate(new Date());
        user.setNameIsUpdate(“N”);//默认初次注册后的登录用户名可以修改一次
        user.setImageUrl(“/uploads/header/default-photo.gif”);
        return user;
    }
    
    /**
     * 返回随机指定位数字符
     */
    public static String getRandomStr(int strLength){
        Random random = new Random();
        char[] ch = “ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefjhijkmnpqrstuvwxyz”.toCharArray();
        String sRand=”“;
        for (int i = 0 ; i < strLength ; i++){
            sRand += String.valueOf(ch[random.nextInt(ch.length)]);
        }
        return sRand;
    }

    /**
     * 根据邮箱名按一定规则生成用户名
     * @param email
     * @return  用户名
     */
    public static synchronized String getUserNameByEmail(String email){
        String userName = null;
        if(StringUtil.validEmail(email)){
            userName = “m” + email.split(“@”)[0] + getRandomStr(4);
        }
        return  userName;

    }


    /**
     * 密码经过md5加密传给bbs论坛
     * @param password 明文密码
     * @return  加密后的密码
     * @throws NoSuchAlgorithmException
     */
    public static synchronized String encodeRealPass(final String password) throws NoSuchAlgorithmException {
        String newPassWord = null;
        if (StringUtils.isNotBlank(password)) {
            newPassWord = MD5.encode(password);
        }
        return newPassWord;
    }


    /**
     * 同步用户信息至论坛
     * @param user 用户信息
     * @param isModifyUserName 是否是修改用户名 1 是   0 否
     */
    public static  void synchBBS(final UserUser user,final String isModifyUserName) {
        try {
            String bbsUrl = Constant.getInstance().getBBSUrl();
            if(StringUtils.isNotEmpty(bbsUrl))
            {
                LOG.info(“sync bbs:” + user.getUserId());
                StringBuffer sb = new StringBuffer(bbsUrl+”/api/sync.php?action=update”);
                sb.append(“&username=”).append(URLEncoder.encode(user.getUserName(), “utf-8”))
                        .append(“&md5_password=”).append(UserUserUtil.encodeRealPass(user.getRealPass())).append(“&user_id=”).append(user.getUserId())//密码经过md5加密后传输
                        .append(“&ip=”).append(“”);
                if((Constant.SYNCH_BBS.IS_MODIFY_UNAME_Y.getCnName()).equals(isModifyUserName)){
                    sb.append(“&update_username=”).append(“true”);
                }
                String strJson = HttpsUtil.requestGet(sb.toString());
                LOG.info(“向BBS同步用户信息,返回的Str:=======================” + strJson);
            }
            else
            {
                LOG.error(“bbs url is null”);
            }

        } catch (Exception ioe) {
            LOG.error(“向BBS同步用户信息异常:” + ioe.getMessage());
        }
    }



    /**
     * –无线代码—
     * 根据第三方昵称和驴妈妈用户名生成-驴妈妈昵称
     * @param cooperationUserName
     * @param userName
     * @return
     */
    public static String getNickName(String cooperationUserName, String userName) {
        // 驴妈妈昵称默认取第三方昵称
        String nickName = cooperationUserName;
        // 第三方昵称为空,则取userName
        if(StringUtils.isBlank(nickName)) {
            nickName = userName;
        }
        // 最终生成的驴妈妈昵称
        String newNickName = null;
        try {
            // 驴妈妈昵称只取17个字节
            newNickName = subStr(nickName, 17);
            // 若是生成的驴妈妈昵称仅截取了第三方昵称的一部分,则在昵称后面加3个点
            if (nickName.length() > newNickName.length()) {
                newNickName = newNickName + “…”;
            }
        } catch (UnsupportedEncodingException e) {
            LOG.error(e);
            newNickName = “”;
        }

        return newNickName;
    }

    /**
     * –无线代码—
     * 截取指定字节数的字符串
     * @param str 需要被截取的字符串
     * @param subSLength 需要截取的字节数
     * @return
     * @throws UnsupportedEncodingException
     * @return 截取完成的字符串
     */
    public static String subStr(String str, int subSLength) throws UnsupportedEncodingException {
        if (null == str) {
            return “”;
        }
        int tempSubLength = subSLength;// 截取字节数
        String subStr = str.substring(0, str.length() < subSLength ? str.length() : subSLength);// 截取的子串
        int subStrByetsL = subStr.getBytes(“UTF-8”).length;// 截取子串的字节长度
        // 说明截取的字符串中包含有汉字
        while (subStrByetsL > tempSubLength) {
            int subSLengthTemp = –subSLength;
            subStr = str.substring(0, subSLengthTemp > str.length() ? str.length() : subSLengthTemp);
            subStrByetsL = subStr.getBytes(“UTF-8”).length;
        }
        return subStr;
    }

}