com.qatickets.service.UserService.java Source code

Java tutorial

Introduction

Here is the source code for com.qatickets.service.UserService.java

Source

/*
The MIT License (MIT)
    
Copyright (c) 2015 QAXML Pty Ltd
    
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
    
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
    
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.qatickets.service;

import java.util.Date;
import java.util.UUID;

import javax.inject.Inject;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.qatickets.dao.UserDao;
import com.qatickets.domain.EmailMessage;
import com.qatickets.domain.UserProfile;

@Service
public class UserService {

    private static final int DEFAULT_PASSWORD_LENGTH = 8;

    private static final Log log = LogFactory.getLog(UserService.class);

    public static final String ATTR_USER = "user";

    @Inject
    private UserDao dao;

    @Inject
    private TicketService ticketService;

    @Inject
    private LinkService linkService;

    @Inject
    private CommentService commentService;

    @Inject
    private TicketVoteService voteService;

    @Inject
    private TicketActivityEventService eventService;

    @Inject
    private TicketFileAttachmentService screenshotAttachmentService;

    @Inject
    private TicketFileAttachmentService fileAttachmentService;

    @Inject
    private SpamService spamService;

    @Inject
    private EmailMessageService emailMessageService;

    @Inject
    private EmailTemplateService emailTemplateService;

    @Transactional(readOnly = false)
    public void save(UserProfile user) {
        this.dao.save(user);
        log.debug("Saved user: " + user);
    }

    @Transactional(readOnly = true)
    public UserProfile findByEmail(String email) {
        UserProfile user = dao.findByEmail(email);
        log.debug("Loaded user: " + user);
        return user;
    }

    @SuppressWarnings("serial")
    public class EmailAlreadyRegisteredException extends Exception {
    }

    @SuppressWarnings("serial")
    public class EmailNotValidException extends Exception {
    }

    @SuppressWarnings("serial")
    public class ProfileNotFoundException extends Exception {
    }

    @Transactional(readOnly = false)
    public UserProfile saveOrUpdateUser(UserProfile currentUser, String userName, String email, int timezone,
            int userId) throws Exception {

        UserProfile profile = null;

        userName = spamService.clean(StringUtils.trim(userName), 32);
        email = spamService.clean(StringUtils.trim(email), 128);

        if (false == this.isValidEmail(email)) {
            throw new EmailNotValidException();
        }

        if (userId == 0) {

            // new user
            profile = new UserProfile();
            profile.setDate(new Date());

            final String password = RandomStringUtils.randomAlphanumeric(DEFAULT_PASSWORD_LENGTH);

            profile.setPassword(password);

        } else {

            profile = this.findById(userId);

            if (profile == null) {
                throw new ProfileNotFoundException();
            }

            // if not the same user or owner, quit
            if (false == currentUser.equals(profile)) {
                throw new ProfileNotFoundException();
            }

        }

        if (profile.isNew() || false == profile.getEmail().equals(email)) {

            log.debug("Email was asked to changed/set to: " + email + " for " + profile);

            if (this.isEmailRegistered(email)) {
                log.debug("The e-mail address is used by other user");
                throw new EmailAlreadyRegisteredException();
            }

            profile.setEmail(email);

        }

        profile.setName(userName);
        profile.setTimezone(timezone);

        this.save(profile);

        // TODO send email to both owner and new user with the new password

        log.debug("User saved: " + profile);

        return profile;

    }

    @Transactional(readOnly = true)
    public UserProfile findById(int id) {
        return dao.findOne(id);
    }

    @Transactional(readOnly = true)
    public UserProfile findByUuid(String uuid) {
        return dao.findByUuid(uuid);
    }

    @Transactional(readOnly = true)
    public boolean isEmailRegistered(String email) {
        return this.dao.findByEmail(email) != null;
    }

    public boolean isValidEmail(String email) {
        return StringUtils.isNotBlank(email) && email.length() <= 128
                && EmailValidator.getInstance().isValid(email);
    }

    @Transactional(readOnly = false)
    public void updatePassword(int id, String current, String newPassword) {

        UserProfile user = this.findById(id);

        if (user.matchPassword(current) && StringUtils.isNotBlank(newPassword)) {
            user.setPassword(newPassword);
            this.save(user);
        }

    }

    @Transactional(readOnly = false)
    public void resetPassword(String email) {

        UserProfile profile = this.findByEmail(email);

        if (profile != null) {

            profile.setPasswordResetToken(UUID.randomUUID().toString());
            this.save(profile);

            // generate "reset password" email
            //         EmailMessage emailMessage = emailTemplateService.generateRestorePasswordEmail(profile);

            // save to emails
            //         this.emailMessageService.save(emailMessage);

        }
    }

    @Transactional(readOnly = true)
    public UserProfile findByPasswordResetToken(String token) {
        return dao.findByPasswordResetToken(token);
    }

    @Transactional(readOnly = false)
    public boolean exists(String email) {
        return this.dao.exists(email) > 0;
    }

    @Transactional(readOnly = false)
    public void resetPassword(String password, String uuid) {

        UserProfile user = this.findByPasswordResetToken(uuid);

        if (user != null) {
            user.setPassword(password);
            user.setPasswordResetToken(null);
            this.save(user);
        }

    }

    @Transactional(readOnly = false)
    public void delete(int id) {
        this.dao.delete(id);
    }

}