<commit_before>/*
 * Copyright(C) 2014 tAsktoys. All rights reserved.
 */
package com.tasktoys.archelon.controller;

import com.tasktoys.archelon.data.entity.User;
import com.tasktoys.archelon.service.UserService;
import java.util.Calendar;
import java.util.Map;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author YuichiroSato
 * @since 0.1
 * @version 0.1
 */
@Controller
@RequestMapping(value = "/usersetting")
@SessionAttributes(UserSession.SESSION_NAME)
public class UsersettingController {

    @Autowired
    private UserService userService;

    /**
     * User setting view.
     */
    protected final static String VIEW = "usersetting";
    protected static final String REDIRECT = "redirect:/" + VIEW;

    private static final String ID = "id";
    private static final String CULLENT_VALUE_PREFIX = "current_";

    private static final String PASSWORD = "<PASSWORD>";

    private static final String USERSETTING = "usersetting";
    private static final String PASSWORD_RESET = "<PASSWORD>";
    private static final String WITHDRAW = "withdraw";

    private enum Param {

        USER_NAME, NEW_USER_PASSWORD, NEW_USER_PASSWORD_R, EMAIL, DESCRIPTION, BIRTHDATE, LOCATION,
        AFFILIATE, URL, TWITTERID, FACEBOOKID;

        @Override
        public String toString() {
            return name().toLowerCase();
        }
    }

    private enum Error {

        NAME_MISS, USER_NAME_DUPLICATE, PASSWORD_MISS, PASSWORD_MISSMATCH,
        EMAIL_MISS, EMAIL_INVALID, BIRTHDATE_FUTURE, BIRTHDATE_INVALID,
        USERSETTING_PASSWORD_MISSMATCH, PASSWORDRESET_PASSWORD_MISSMATCH,
        WITHDRAW_PASSWORD_MISSMATCH;

        @Override
        public String toString() {
            return name().toLowerCase();
        }
    }

    @RequestMapping(method = RequestMethod.GET)
    public String handleEmptyRequest(Model model) {
        model.addAttribute(ID, "Guest");
        return VIEW;
    }

    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public String handleIdRequest(@PathVariable String id, Model model, UserSession userSession,
            RedirectAttributes redirect) {
        if (!id.equals(userSession.getName())) {
            redirect.addFlashAttribute(ErrorController.ATTR_MESSAGE, "error.access.permission");
            return ErrorController.REDIRECT;
        }
        model.addAttribute(ID, id);
        setUserValueToForm(model, userSession.getUser());
        return VIEW;
    }

    @RequestMapping(value = USERSETTING, method = RequestMethod.POST)
    public String handleUserSetting(@RequestParam Map<String, String> params, Model model, UserSession userSession,
            RedirectAttributes redirect) {
        model.addAttribute(ID, userSession.getName());
        redirect.addAttribute(ID, userSession.getName());
        if (isCorrectPassword(userSession, params)) {
            return updateUserInformation(redirect, params, userSession);
        } else {
            return errorHandle(model, Error.USERSETTING_PASSWORD_MISSMATCH.toString());
        }
    }

    @RequestMapping(value = PASSWORD_RESET, method = RequestMethod.POST)
    public String handlePasswordReset(@RequestParam Map<String, String> params, Model model, UserSession userSession) {
        model.addAttribute(ID, userSession.getName());
        if (isCorrectPassword(userSession, params)) {
            return resetPassword(model, params, userSession);
        } else {
            return errorHandle(model, Error.PASSWORDRESET_PASSWORD_MISSMATCH.toString());
        }
    }

    @RequestMapping(value = WITHDRAW, method = RequestMethod.POST)
    public String handleWithdraw(@RequestParam Map<String, String> params, Model model, UserSession userSession) {
        model.addAttribute(ID, userSession.getName());
        if (isCorrectPassword(userSession, params)) {
            return setUserStateToDeleted(userSession);
        } else {
            return errorHandle(model, Error.WITHDRAW_PASSWORD_MISSMATCH.toString());
        }
    }

    private void setUserValueToForm(Model model, User user) {
        Map<String, String> map = user.toSecureMap();
        for (String key : map.keySet()) {
            model.addAttribute(CULLENT_VALUE_PREFIX + key, map.get(key));
        }
    }

    private boolean isCorrectPassword(UserSession userSession, Map<String, String> params) {
        User user = userSession.getUser();
        String password = params.get(PASSWORD);
        return user.isValidPasswordWithPlaneString(password);
    }

    private String updateUserInformation(RedirectAttributes model, Map<String, String> params, UserSession userSession) {
        User.Builder builder = new User.Builder();

        builder.id(userSession.getUser().getId());
        // Get required fields.
        String userName = params.get(Param.USER_NAME.toString());
        String email = params.get(Param.EMAIL.toString());

        if (userName == null || userName.isEmpty()) {
            return errorHandle(model, Error.NAME_MISS.toString());
        }
        if (!userSession.getName().equals(userName) && userService.findUserByName(userName) != null) {<commit_msg>Bug fix on UsersettingController #43 <commit_after>/*
 * Copyright(C) 2014 tAsktoys. All rights reserved.
 */
package com.tasktoys.archelon.controller;

import com.tasktoys.archelon.data.entity.User;
import com.tasktoys.archelon.service.UserService;
import java.util.Calendar;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author YuichiroSato
 * @since 0.1
 * @version 0.1
 */
@Controller
@RequestMapping(value = "/usersetting")
@SessionAttributes(UserSession.SESSION_NAME)
public class UsersettingController {

    @Autowired
    private UserService userService;
    static final Logger log = Logger.getLogger(UsersettingController.class.getName());

    /**
     * User setting view.
     */
    protected final static String VIEW = "usersetting";
    protected static final String REDIRECT = "redirect:/" + VIEW;

    private static final String ID = "id";
    private static final String CULLENT_VALUE_PREFIX = "current_";

    private static final String PASSWORD = "<PASSWORD>";

    private static final String USERSETTING = "usersetting";
    private static final String PASSWORD_RESET = "passwordreset";
    private static final String WITHDRAW = "withdraw";

    private enum Param {

        USER_NAME, NEW_USER_PASSWORD, NEW_USER_PASSWORD_R, EMAIL, DESCRIPTION, BIRTHDATE, LOCATION,
        AFFILIATE, URL, TWITTERID, FACEBOOKID;

        @Override
        public String toString() {
            return name().toLowerCase();
        }
    }

    private enum Error {

        NAME_MISS, USER_NAME_DUPLICATE, PASSWORD_MISS, PASSWORD_MISSMATCH,
        EMAIL_MISS, EMAIL_INVALID, BIRTHDATE_FUTURE, BIRTHDATE_INVALID,
        USERSETTING_PASSWORD_MISSMATCH, PASSWORDRESET_PASSWORD_MISSMATCH,
        WITHDRAW_PASSWORD_MISSMATCH;

        @Override
        public String toString() {
            return name().toLowerCase();
        }
    }

    @RequestMapping(method = RequestMethod.GET)
    public String handleEmptyRequest(Model model) {
        model.addAttribute(ID, "Guest");
        return VIEW;
    }

    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public String handleIdRequest(@PathVariable String id, Model model, UserSession userSession,
            RedirectAttributes redirect) {
        if (!id.equals(userSession.getName())) {
            redirect.addFlashAttribute(ErrorController.ATTR_MESSAGE, "error.access.permission");
            return ErrorController.REDIRECT;
        }
        model.addAttribute(ID, id);
        setUserValueToForm(model, userSession.getUser());
        return VIEW;
    }

    @RequestMapping(value = USERSETTING, method = RequestMethod.POST)
    public String handleUserSetting(@RequestParam Map<String, String> params, Model model, UserSession userSession,
            RedirectAttributes redirect) {
        model.addAttribute(ID, userSession.getName());
        redirect.addAttribute(ID, userSession.getName());
        if (isCorrectPassword(userSession, params)) {
            return updateUserInformation(redirect, params, userSession);
        } else {
            setUserValueToForm(model, userSession.getUser());
            return errorHandle(model, Error.USERSETTING_PASSWORD_MISSMATCH.toString());
        }
    }

    @RequestMapping(value = PASSWORD_RESET, method = RequestMethod.POST)
    public String handlePasswordReset(@RequestParam Map<String, String> params, Model model, UserSession userSession) {
        model.addAttribute(ID, userSession.getName());
        if (isCorrectPassword(userSession, params)) {
            return resetPassword(model, params, userSession);
        } else {
            return errorHandle(model, Error.PASSWORDRESET_PASSWORD_MISSMATCH.toString());
        }
    }

    @RequestMapping(value = WITHDRAW, method = RequestMethod.POST)
    public String handleWithdraw(@RequestParam Map<String, String> params, Model model, UserSession userSession) {
        model.addAttribute(ID, userSession.getName());
        if (isCorrectPassword(userSession, params)) {
            return setUserStateToDeleted(userSession);
        } else {
            return errorHandle(model, Error.WITHDRAW_PASSWORD_MISSMATCH.toString());
        }
    }

    private void setUserValueToForm(Model model, User user) {
        Map<String, String> map = user.toSecureMap();
        for (String key : map.keySet()) {
            if (key.equals("birthdate"))
                model.addAttribute(CULLENT_VALUE_PREFIX + key, decrementMonth(map.get(key)));
            else
                model.addAttribute(CULLENT_VALUE_PREFIX + key, map.get(key));
        }
    }
    
    private String decrementMonth(String date) {
        log.log(Level.INFO, date);
        if (date != null && !date.isEmpty()) {
            // date format is year-month-date
            String[] yyyy_mm_dd = date.split("-");
            int mm = Integer.parseInt(yyyy_mm_dd[1]) - 1;
        log.log(Level.INFO, yyyy_mm_dd[0] + "-" + String.valueOf(mm) + "-" + yyyy_mm_dd[2]);
        if (mm < 10)
                return yyyy_mm_dd[0] + "-0" + String.valueOf(mm) + "-" + yyyy_mm_dd[2];
            else
                return yyyy_mm_dd[0] + "-" + String.valueOf(mm) + "-" + yyyy_mm_dd[2];
        }
        return date;
    }

    private boolean isCorrectPassword(UserSession userSession, Map<String, String> params) {
        User user = userSession.getUser();
        String password = params.get(PASSWORD);
        return user.isValidPasswordWithPlaneString(password);
    }

    private String updateUserInformation(RedirectAttributes model, Map<String, String> params, UserSession userSession) {
        User.Builder builder = new User.Builder();

        builder.id(userSession.getUser().getId());
        // Get required fields.
        String userName = params.get(Param.USER_NAME.toString());
        String email = params.get(Param.EMAIL.toString());

        if (userName == null || userName.isEmpty()) {
            return errorHandle(model, Error.NAME_MISS.toString());
        }
        if (!userSession.getName().equals(userName) && userService.findUserByName(userName) != null) {
{'fraction_non_alphanumeric': 0.10350125333548961, 'fraction_numerical': 0.0023449502708821866, 'mean_word_length': 3.316928446771379, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5452415', 'n_tokens_mistral': 3487, 'n_tokens_neox': 3425, 'n_words': 726}