easycare.web.user.NewUserForm.java Source code

Java tutorial

Introduction

Here is the source code for easycare.web.user.NewUserForm.java

Source

package easycare.web.user;

import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Sets;
import easycare.model.ContactInformation;
import easycare.model.Country;
import easycare.model.Location;
import easycare.model.Organisation;
import easycare.model.User;
import easycare.model.UserLocationAccess;
import easycare.model.security.Role;
import easycare.model.security.RoleEnum;
import easycare.model.validation.FieldMatch;
import easycare.service.RoleService;
import easycare.service.SessionSecurityService;
import easycare.web.password.ChangePasswordForm;
import easycare.web.password.PasswordMethodManual;
import easycare.web.validation.LocationAccess;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.joda.time.LocalDate;
import org.springframework.security.access.AccessDeniedException;

import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Sets.newHashSet;
import static org.apache.commons.collections.CollectionUtils.isEmpty;

@LocationAccess
@FieldMatch(first = "password", second = "username", message = "{FieldMatch.user.password}", globalError = false, field1Error = true, field2Error = false, negate = true, groups = PasswordMethodManual.class)
public class NewUserForm extends BaseUserFormWithEmailOption implements IUserPermissionForm {
    public static final String PASSWORD_METHOD_AUTO = "auto";
    public static final String PASSWORD_METHOD_MANUAL = "manual";

    @NotEmpty
    @Length(min = User.USERNAME_LENGTH_MIN, max = User.USERNAME_LENGTH_MAX)
    @Pattern(regexp = User.USERNAME_VALIDATION_REGEXP_V2)
    private String username;

    @NotEmpty
    private String passwordMethod = PASSWORD_METHOD_AUTO;

    @NotEmpty(groups = PasswordMethodManual.class, message = "{NotEmpty.password}")
    @Pattern(regexp = ChangePasswordForm.PASSWORD_STRING_REGEX, groups = PasswordMethodManual.class, message = "{Pattern.password}")
    private String password;

    @Valid
    private ContactInformation contactInformation;

    private List<String> locations;

    private UserLocationAccess userLocationAccess = UserLocationAccess.ALL;

    @NotEmpty
    private List<String> userRoles;

    public NewUserForm() {
    }

    public NewUserForm(Country country) {
        contactInformation = new ContactInformation(country);
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public void setUsername(String username) {
        this.username = username;
    }

    public String getPasswordMethod() {
        return passwordMethod;
    }

    public void setPasswordMethod(String passwordMethod) {
        this.passwordMethod = passwordMethod;
    }

    public boolean isPasswordMethodAuto() {
        return PASSWORD_METHOD_AUTO.equals(passwordMethod);
    }

    public boolean isPasswordMethodManual() {
        return PASSWORD_METHOD_MANUAL.equals(passwordMethod);
    }

    public boolean isInterpretingPhysicianDisabled() {
        return !hasRole(RoleEnum.ROLE_CLINICIAN);
    }

    public boolean hasRole(RoleEnum role) {
        return userRoles != null && userRoles.contains(role.toString());
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public List<String> getLocations() {
        return locations;
    }

    public void setLocations(List<String> locations) {
        this.locations = locations;
    }

    public List<String> getUserRoles() {
        return userRoles;
    }

    public void setUserRoles(List<String> userRoles) {
        this.userRoles = userRoles;
    }

    public User createUser(SessionSecurityService securityService, RoleService roleService, LocalDate currentDate) {
        User user = new User(userOrganisation(securityService));
        user.setNames(getFirstName(), getLastName());
        user.setTitle(getTitle());
        user.setUsername(username);
        user.setPassword(password, currentDate);

        if (userLocationAccess.equals(UserLocationAccess.SPECIFIC)) {
            List<Location> locationList = transformValidLocations(securityService);
            user.addLocations(locationList.toArray(new Location[locationList.size()]));
        } else {
            user.useAllLocations();
        }

        user.addRoles(transformValidRoles(roleService, securityService));
        user.setEmail(getEmail());
        user.setLicenseNumber(getLicenseNumber());
        user.setContactInformation(contactInformation);
        user.setIdentificationNumber(getIdentificationNumber());
        return user;
    }

    // TODO 9/1/11 fotini & mitko should move into service layer to protect user
    // save
    private Set<Role> transformValidRoles(RoleService roleService, SessionSecurityService securityService) {
        Set<Role> filteredRoles = filterRoles(roleService, securityService);
        if (isEmpty(filteredRoles)) {
            throw new AccessDeniedException("Cannot access the selected roles");
        }
        return filteredRoles;
    }

    private Set<Role> filterRoles(RoleService roleService, SessionSecurityService securityService) {
        if (isEmpty(userRoles)) {
            return newHashSet();
        }

        Set<Role> userViewableRoles = roleService.findUserViewableRoles(securityService.getCurrentUserDetails());
        return Sets.filter(userViewableRoles, new Predicate<Role>() {
            @Override
            public boolean apply(Role role) {
                return userRoles.contains(role.getName().name());
            }
        });
    }

    private Organisation userOrganisation(SessionSecurityService securityService) {
        User currentUser = securityService.getCurrentUser();
        return currentUser.getOrganisation();
    }

    // TODO 9/1/11 fotini & mitko should move into service layer to protect user
    // save
    private List<Location> transformValidLocations(SessionSecurityService securityService) {
        if (hasAllLocationsAccess()) {
            return newArrayList();
        }

        ArrayList<Location> filteredLocations = filterSpecificLocations(securityService);
        if (isEmpty(filteredLocations)) {
            throw new AccessDeniedException("Cannot access the selected locations");
        }
        return filteredLocations;
    }

    private boolean hasAllLocationsAccess() {
        return UserLocationAccess.ALL.equals(userLocationAccess);
    }

    private ArrayList<Location> filterSpecificLocations(SessionSecurityService securityService) {
        if (isEmpty(locations)) {
            return newArrayList();
        }

        List<Location> userLocations = userLocations(securityService);
        return newArrayList(Collections2.filter(userLocations, new Predicate<Location>() {
            @Override
            public boolean apply(Location location) {
                return locations.contains(String.valueOf(location.getId()));
            }
        }));
    }

    private List<Location> userLocations(SessionSecurityService securityService) {
        return securityService.getCurrentUser().getAssignedLocations();
    }

    @Override
    public UserLocationAccess getUserLocationAccess() {
        return userLocationAccess;
    }

    public void setUserLocationAccess(UserLocationAccess userLocationAccess) {
        this.userLocationAccess = userLocationAccess;
    }

    public ContactInformation getContactInformation() {
        return contactInformation;
    }

    public void setContactInformation(ContactInformation contactInformation) {
        this.contactInformation = contactInformation;
    }

    public String createAuditDescription() {
        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append("username", username)
                .append("email", getEmail()).append("roles", userRoles)
                .append("locations", hasAllLocationsAccess() ? "all" : locations).toString();
    }
}