tw.com.softleader.sportslottery.setting.web.UserAction.java Source code

Java tutorial

Introduction

Here is the source code for tw.com.softleader.sportslottery.setting.web.UserAction.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package tw.com.softleader.sportslottery.setting.web;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import tw.com.softleader.sportslottery.setting.entity.DepositCardEntity;
import tw.com.softleader.sportslottery.setting.entity.UserEntity;
import tw.com.softleader.sportslottery.setting.service.DepositCardService;
import tw.com.softleader.sportslottery.setting.service.UserService;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport {
    private static final long serialVersionUID = 2014L;

    @Autowired
    private UserService service;
    @Autowired
    private DepositCardService cardService;

    private UserEntity model;
    private String oldUserPassword;
    private String userPassword;
    private String confirm_password;
    private List<UserEntity> models;
    private Logger log = LoggerFactory.getLogger(UserAction.class);
    private String json;
    private InputStream inputStream;
    private LocalDate time;
    private String to;
    private String account;
    private String cardAccount;
    private Long coins; //?coinscoins
    private String lockCharacter;

    private Locale locale = ActionContext.getContext().getLocale();

    public Locale getLocale() {
        return locale;
    }

    public String getLockCharacter() {
        return lockCharacter;
    }

    public void setLockCharacter(String lockCharacter) {
        this.lockCharacter = lockCharacter;
    }

    public String getOldUserPassword() {
        return oldUserPassword;
    }

    public void setOldUserPassword(String oldUserPassword) {
        this.oldUserPassword = oldUserPassword;
    }

    public String getConfirm_password() {
        return confirm_password;
    }

    public void setConfirm_password(String confirm_password) {
        this.confirm_password = confirm_password;
    }

    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public Long getCoins() {
        return coins;
    }

    public void setCoins(Long coins) {
        this.coins = coins;
    }

    public String getCardAccount() {
        return cardAccount;
    }

    public void setCardAccount(String cardAccount) {
        this.cardAccount = cardAccount;
    }

    public String getCardPassword() {
        return cardPassword;
    }

    public void setCardPassword(String cardPassword) {
        this.cardPassword = cardPassword;
    }

    private String cardPassword;

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public void setTime(LocalDate time) {
        this.time = time;
    }

    public void setModel(UserEntity model) {
        this.model = model;
    }

    public String getJson() {
        return json;
    }

    public UserEntity getModel() {
        return model;
    }

    public List<UserEntity> getModels() {
        return models;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    @Override
    public void validate() {
        if (userPassword != null && userPassword.length() > 0) {
            model.setUserPassword(userPassword.getBytes());
        }
    }

    //
    public void iValidate(int select) {
        getFieldErrors().clear();
        if (model != null) {
            switch (select) {
            case 1:
                log.debug("iValidate...(...");
                if (model.getUserAccount() != null && model.getUserAccount().matches("^[a-zA-Z0-9]\\S{5,}$")) {
                    this.check();
                } else {
                    this.addFieldError("username", this.getText("invalid.fieldvalue.id"));
                    log.debug("?" + model.getUserAccount());
                }
                if (userPassword == null || userPassword.length() < 5 || !userPassword.matches(".*[0-9].*")
                        || !userPassword.matches(".*[A-Za-z].*") || !userPassword.matches("^[a-zA-Z0-9]+$")) {
                    this.addFieldError("password", this.getText("invalid.fieldvalue.password"));
                    log.debug("?" + userPassword);
                }
                if (confirm_password == null || !confirm_password.equals(userPassword)) {
                    this.addFieldError("confirm_password", this.getText("invalid.fieldvalue.confirm_password"));
                    log.debug("??" + confirm_password + ":" + userPassword);
                }
                if (model.getUserBirthday() != null) {
                    try {
                        LocalDate checkDate = new LocalDate();
                        if ((checkDate.getValue(0) - model.getUserBirthday().getValue(0)) < 18
                                || ((checkDate.getValue(0) - model.getUserBirthday().getValue(0)) == 18
                                        && (model.getUserBirthday().getValue(1) - checkDate.getValue(1)) > 0)
                                || ((checkDate.getValue(0) - model.getUserBirthday().getValue(0)) == 18
                                        && (model.getUserBirthday().getValue(1) - checkDate.getValue(1)) == 0
                                        && (model.getUserBirthday().getValue(2) - checkDate.getValue(2) > 0))) {
                            addFieldError("userBirth", this.getText("invalid.fieldvalue.birth"));
                            log.debug(checkDate + "?" + model.getUserBirthday());
                        }
                    } catch (Exception e) {
                        addFieldError("userBirth", this.getText("invalid.fieldvalue.birth"));
                        log.debug("??");
                    }
                }
                if (model.getUserEmail() != null && model.getUserEmail()
                        .matches("^[_a-z0-9-]+([.][_a-z0-9-]+)*@[a-z0-9-]+([.][a-z0-9-]+)*$")) {
                    this.checkEmail().equals("error");
                } else {
                    addFieldError("mail", "mail??");
                    log.debug("Email???");
                }
                if (model.getUserName() == null || !model.getUserName().matches("^[\\u4E00-\\u9FA5]+$")) {
                    addFieldError("name", this.getText("invalid.fieldvalue.name"));
                    log.debug("???" + model.getUserName());
                }
                if (model.getUserCardId() != null && isValidTWPID(model.getUserCardId())) {
                    this.checkUserCardId();
                } else {
                    this.addFieldError("userCardId", this.getText("invalid.fieldvalue.cardid"));
                    log.debug("?");
                }
                if (model.getUserPhone() != null && model.getUserPhone().length() < 14) {
                    try {
                        Double userBank = Double.parseDouble(model.getUserPhone());
                    } catch (NumberFormatException e) {
                        this.addFieldError("phone", this.getText("invalid.fieldvalue.bank"));
                        log.debug("?");
                    }
                } else {
                    this.addFieldError("phone", this.getText("invalid.fieldvalue.phone"));
                    log.debug("???");
                }
                if (model.getUserBankAccount() != null
                        && model.getUserBankAccount().replaceAll("-", "").length() == 14
                        && !model.getUserBankAccount().matches(".*[eE].*")) {
                    String temp = model.getUserBankAccount().replaceAll("-", "");
                    try {
                        Double userBank = Double.parseDouble(temp);
                    } catch (NumberFormatException e) {
                        this.addFieldError("userBankAccount", this.getText("invalid.fieldvalue.bank"));
                        log.debug("?");
                    }
                } else {
                    this.addFieldError("userBankAccount", this.getText("invalid.fieldvalue.bank"));
                    log.debug("??" + model.getUserBankAccount());
                }
                break;
            case 2:
                log.debug("iValidate...(2");
                break;
            default:
                break;
            }
        }
    }

    public String onLock() {
        Map session = ActionContext.getContext().getSession();
        UserEntity user = (UserEntity) session.get("user");
        log.debug(user.getUserState());
        log.debug(lockCharacter);
        if (user.getUserState().equals(lockCharacter)) {
            user.setUserState("0");
            session.remove("locking");
            user = service.noPswdUpdate(user);
            session.put("user", user);
        } else {
            log.debug("?");
            return ERROR;
        }
        return SUCCESS;
    }

    public String sendLock() {
        Map session = ActionContext.getContext().getSession();
        UserEntity user = (UserEntity) session.get("user");
        return service.sendLockmail(user);
    }

    //?
    public String forgetPassword() {
        String message = null;
        int ret = service.forgetPassword(to, account);
        switch (ret) {
        case 0:
            return SUCCESS;
        case 1:
            message = new Gson().toJson(getText("invalid.fieldvalue.forget.email"));
            //addFieldError("emailCheck", getText("invalid.fieldvalue.forget.email")); 
            break;
        case 2:
            message = new Gson().toJson(this.getText("invalid.fieldvalue.forget.account"));
            //this.addFieldError("accountCheck", this.getText("invalid.fieldvalue.forget.account"));
            break;
        default:
            message = new Gson().toJson(this.getText("invalid.fieldvalue.other"));
            //this.addFieldError("orther", this.getText("invalid.fieldvalue.other"));
            break;
        }
        inputStream = new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8));
        //inputStream = new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8));
        return ERROR;
    }

    //?coins
    public String coinsUpdate() {
        String message = null;
        Map session = ActionContext.getContext().getSession();
        UserEntity user = (UserEntity) session.get("user");
        if (coins == null) {
            //log.debug(""+user);
            //
            DepositCardEntity card = cardService.findByCardAccount(cardAccount, cardPassword);
            if (card != null) {
                try {
                    if (card.isState()) {
                        user.setCoins(user.getCoins() + card.getPoint());
                        //log.debug("coins"+card.getPoint());
                        message = card.getPoint().toString();
                        card.setUserId(user);
                        card.setState(false);
                        service.noPswdUpdate(user);
                        log.debug("?");
                        card.setUseTime(LocalDateTime.now());
                        cardService.update(card);
                    } else {
                        log.debug("?");
                        //                  this.addFieldError("cardError",
                        //                        this.getText("alreadyuse.card"));
                        message = "error ?";
                    }
                } catch (Exception e) {
                    log.debug("coins");
                    //               this.addFieldError("cardError",
                    //                     this.getText("fieldvalue.card"));
                    message = "error coins";
                    e.printStackTrace();
                }
            } else {
                log.debug("?");
                this.addFieldError("cardError", this.getText("fieldvalue.card"));
                message = "error ?";
            }
            log.debug("coins?");
        } else {
            try {
                user.setCoins(user.getCoins() + coins);
                message = new Gson().toJson(service.update(user));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        inputStream = new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8));
        return "message";
    }

    //?
    @Override
    public String execute() throws Exception {
        System.out.println("UserAction execute");
        json = new Gson().toJson(service.getAll());
        inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
        return SUCCESS;
    }

    //
    public String insert() throws Exception {
        log.debug("");
        this.iValidate(1);//
        if (this.getFieldErrors().isEmpty()) {
            model.setCreator("Guest"); //
            model.setModifier("Guest"); //
            model.setCreateTime(LocalDateTime.now());
            model.setModifiedTime(LocalDateTime.now());
            model.setCoins(0l);
            model.setUserState(new String(service.getNewPassword()));
            String cardId = model.getUserCardId().toUpperCase();
            model.setUserCardId(cardId);
            //model.setUserPassword(userPassword.getBytes());
            log.debug("Model = {}", model);

            try {
                service.insert(service.encoding(model));
                UserEntity entity = service.getByUserAccount(model.getUserAccount());
                log.debug("" + entity);
                Map<String, UserEntity> session = (Map) ServletActionContext.getContext().getSession();
                session.put("user", entity);
                log.debug("?");
            } catch (Exception e) {
                log.debug("!!!!");
                this.addFieldError("other", this.getText("invalid.fieldvalue.other"));
                e.printStackTrace();
                return ERROR;
            }
            return SUCCESS;
        } else {
            log.debug("" + getFieldErrors().toString());
            return ERROR;
        }
    }

    //?
    public String select() {
        HttpServletRequest request = ServletActionContext.getRequest();
        Map session = ActionContext.getContext().getSession();
        UserEntity userEntity = (UserEntity) session.get("user");

        json = new Gson().toJson(userEntity);
        inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));

        return "select";
    }

    //
    public String update() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        Map session = ActionContext.getContext().getSession();
        UserEntity userEntity = (UserEntity) session.get("user");

        if (getFieldErrors().isEmpty()) {
            log.debug("");
            log.debug("Model = {}", model);
            model.setModifier("Guest");
            model.setModifiedTime(LocalDateTime.now());
            //log.debug(""+userEntity);
            try {
                if (model != null) {
                    log.debug(":" + userPassword);
                    if (userPassword != null && userPassword.length() > 5) {
                        model.setUserPassword(oldUserPassword.getBytes());
                        model = service.encoding(model);
                        if (userEntity != null
                                && Arrays.equals(userEntity.getUserPassword(), model.getUserPassword())) {
                            log.debug("? ?");

                            model.setUserPassword(userPassword.getBytes());
                        } else {
                            log.debug("??");
                            this.addFieldError("passwordError", this.getText("invalid.fieldvalue.password"));
                            return ERROR;
                        }
                    }
                    userEntity.setUserPassword(service.encoding(model).getUserPassword());
                    userEntity.setUserName(model.getUserName());
                    userEntity.setUserBirthday(model.getUserBirthday());
                    userEntity.setUserEmail(model.getUserEmail());
                    userEntity.setUserPhone(model.getUserPhone());
                    service.update(userEntity);
                    log.debug("!!?!!");
                    request.setAttribute("updateSuccess", "?");
                }
            } catch (Exception e) {
                log.debug("!!!!");
                this.addFieldError("other", this.getText("invalid.fieldvalue.other"));
                request.setAttribute("updateFail", "");
                e.printStackTrace();
            }
            return SUCCESS;
        }
        return ERROR;
    }

    // 
    public String checkUser() {
        log.debug(model.getUserAccount() + " : " + model.getUserPassword());
        UserEntity entity = service.checkLogin(model.getUserAccount(), service.encoding(model));
        if (entity != null) {
            log.debug("?");
            inputStream = new ByteArrayInputStream("true".getBytes(StandardCharsets.UTF_8));
        } else {
            log.debug("");
            addFieldError("LoginFail", "?");
            inputStream = new ByteArrayInputStream("false".getBytes(StandardCharsets.UTF_8));
        }
        return "checkUser";
    }

    // 
    public String updateUserInfo() {
        HttpServletRequest request = ServletActionContext.getRequest();
        Map session = ActionContext.getContext().getSession();
        UserEntity userEntity = (UserEntity) session.get("user");

        log.debug("");
        log.debug("Model = {}", model);
        model.setModifier("Guest");
        model.setModifiedTime(LocalDateTime.now());
        // log.debug(""+userEntity);
        try {
            if (model != null) {
                model = service.encoding(model);
                userEntity.setUserPassword(model.getUserPassword());
                userEntity.setUserName(model.getUserName());
                userEntity.setUserBirthday(model.getUserBirthday());
                userEntity.setUserEmail(model.getUserEmail());
                userEntity.setUserPhone(model.getUserPhone());
                service.update(userEntity);
                log.debug("!!?!!");
                inputStream = new ByteArrayInputStream("true".getBytes(StandardCharsets.UTF_8));
            }
        } catch (Exception e) {
            log.debug("!!!!");
            inputStream = new ByteArrayInputStream("false".getBytes(StandardCharsets.UTF_8));
            e.printStackTrace();
        }
        return "updateUserInfo";
    }

    //
    public String updateUserPassword() throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        Map session = ActionContext.getContext().getSession();
        UserEntity userEntity = (UserEntity) session.get("user");
        //log.debug("updateUserPassword()");
        model.setModifier("Guest");
        model.setModifiedTime(LocalDateTime.now());

        if (getFieldErrors().isEmpty()) {
            log.debug("");
            log.debug("Model = {}", model);

            // log.debug(""+userEntity);
            try {
                if (userPassword != null && userPassword.length() > 5) {
                    model.setUserPassword(oldUserPassword.getBytes());
                    model = service.encoding(model);
                    if (userEntity != null
                            && Arrays.equals(userEntity.getUserPassword(), model.getUserPassword())) {
                        model.setUserPassword(userPassword.getBytes());

                        userEntity.setUserPassword(service.encoding(model).getUserPassword());
                        service.update(userEntity);
                        service.updateUserPasswordMail(userEntity);
                        inputStream = new ByteArrayInputStream("true".getBytes(StandardCharsets.UTF_8));
                    } else {
                        log.debug("??");
                        inputStream = new ByteArrayInputStream("false".getBytes(StandardCharsets.UTF_8));
                    }
                }
            } catch (Exception e) {
                log.debug("!!!!");
                inputStream = new ByteArrayInputStream("false".getBytes(StandardCharsets.UTF_8));
                e.printStackTrace();
            }
        }
        return "updateUserPassword";
    }

    //?
    public String checkUserCardId() {
        String result = ERROR;
        String userCardId = model.getUserCardId().toUpperCase();
        //log.debug("??" + userCardId);
        if (service.getByuserCardId(userCardId) == null) {
            result = SUCCESS;
        } else {
            this.addFieldError("userCardId", this.getText("invalid.fieldvalue.cardid"));
        }
        return result;
    }

    public final Pattern TWPID_PATTERN = Pattern.compile("[ABCDEFGHJKLMNPQRSTUVXYWZIO][12]\\d{8}");

    public boolean isValidTWPID(String twpid) {
        boolean result = false;
        String pattern = "ABCDEFGHJKLMNPQRSTUVXYWZIO";
        if (TWPID_PATTERN.matcher(twpid.toUpperCase()).matches()) {
            int code = pattern.indexOf(twpid.toUpperCase().charAt(0)) + 10;
            int sum = 0;
            sum = (int) (code / 10) + 9 * (code % 10) + 8 * (twpid.charAt(1) - '0') + 7 * (twpid.charAt(2) - '0')
                    + 6 * (twpid.charAt(3) - '0') + 5 * (twpid.charAt(4) - '0') + 4 * (twpid.charAt(5) - '0')
                    + 3 * (twpid.charAt(6) - '0') + 2 * (twpid.charAt(7) - '0') + 1 * (twpid.charAt(8) - '0')
                    + (twpid.charAt(9) - '0');
            if ((sum % 10) == 0) {
                result = true;
            } else {
                this.addFieldError("userCardId", this.getText("invalid.fieldvalue.cardid"));
            }
        }
        return result;
    }

    //Email?
    public String checkEmail() {
        String result = ERROR;
        //log.debug("Email?" + model.getUserEmail());
        Map session = ActionContext.getContext().getSession();
        UserEntity userEntity = (UserEntity) session.get("user");
        if (userEntity != null && userEntity.getUserEmail().equals(model.getUserEmail())) {
            return SUCCESS;//
        } else if (model != null && model.getUserEmail().length() > 0) {
            UserEntity check = service.getByUserEmail(model.getUserEmail());
            if (check == null) {
                result = SUCCESS;
            } else {
                //log.debug("Email");
                addFieldError("mail", "Email");
                result = ERROR;
            }
            return result;
        }
        log.debug("modelemail");
        return result;
    }

    //Email?2 ??Email?
    public String checkEmailSelf() {
        //log.debug("Email?" + model.getUserEmail());
        Map session = ActionContext.getContext().getSession();
        UserEntity userEntity = (UserEntity) session.get("user");
        if (userEntity != null && userEntity.getUserEmail().equals(model.getUserEmail())) {
            log.debug("Email");
            inputStream = new ByteArrayInputStream("true".getBytes(StandardCharsets.UTF_8));
        } else if (model != null && model.getUserEmail().length() > 0) {
            UserEntity check = service.getByUserEmail(model.getUserEmail());
            if (check == null) {
                log.debug("??Eamil");
                inputStream = new ByteArrayInputStream("true".getBytes(StandardCharsets.UTF_8));
            } else {
                log.debug("?Email");
                inputStream = new ByteArrayInputStream("false".getBytes(StandardCharsets.UTF_8));
            }
        } else {
            log.debug("Email");
            inputStream = new ByteArrayInputStream("false".getBytes(StandardCharsets.UTF_8));
        }

        return "checkEmailSelf";
    }

    //?
    public String check() {
        String result = ERROR;
        if (model != null && model.getUserAccount().length() > 5) {
            UserEntity check = service.getByUserAccount(model.getUserAccount());
            if (check == null) {
                result = SUCCESS;
            } else {
                //log.debug("");
                addFieldError("account", "");
            }
        } else {
            this.addFieldError("account", this.getText("invalid.fieldvalue.id"));
        }
        return result;
    }

    //
    public String login() throws Exception {
        log.debug("login...");

        // 
        /*
        UserEntity entity2 = service.getById(2l);
        entity2.setUserPassword("a123456".getBytes());
        service.update(service.encoding(entity2));
        UserEntity entity3 = service.getById(3l);
        entity3.setUserPassword("a123456".getBytes());
        service.update(service.encoding(entity3));
        */

        //??
        log.debug(model.getUserAccount() + " : " + model.getUserPassword());
        UserEntity entity = service.checkLogin(model.getUserAccount(), service.encoding(model));
        if (entity != null) {
            Map<String, UserEntity> session = (Map) ServletActionContext.getContext().getSession();
            session.put("user", entity);
            //UserEntity e = session.get("user");
            //log.debug(""+e);
            return SUCCESS;
        } else {
            log.debug("?");
            addFieldError("LoginFail", "?");
            return INPUT;
        }
    }

    //?
    public String searchByAccount() throws Exception {
        log.debug("searchByAccount...");
        json = new Gson().toJson(service.getByUserAccount(model.getUserAccount()));
        inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));

        return "searchByAccount";
    }

    //?
    public String searchByCreateTime() throws Exception {
        log.debug("searchByCreateTime...");

        json = new Gson().toJson(service.getByCreateTime(time));
        inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));

        return "searchByCreateTime";
    }
}