#120 move to services

This commit is contained in:
Anton Romanov 2019-05-23 16:02:44 +04:00
parent 457f1da985
commit c303d65c8d
8 changed files with 512 additions and 362 deletions

View File

@ -126,6 +126,6 @@ dependencies {
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.0'
testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test'
testCompile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1'
compile group: 'org.seleniumhq.selenium', name: 'selenium-java', version: '3.3.1'
}

View File

@ -0,0 +1,52 @@
package ru.ulstu.grant.page;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
public class KiasPage {
private WebDriver driver;
public KiasPage(WebDriver webDriver) {
this.driver = webDriver;
}
public List<WebElement> getGrants() {
List<WebElement> grants = new ArrayList<>();
do {
grants.addAll(getPageOfGrants());
}
while (checkPagination());
return grants;
}
public List<WebElement> getPageOfGrants() {
WebElement listContest = driver.findElement(By.tagName("tBody"));
List<WebElement> grants = listContest.findElements(By.cssSelector("tr.tr"));
return grants;
}
public boolean checkPagination() {
try {
if (driver.findElements(By.id("js-ctrlNext")).size() > 0) {
driver.findElement(By.id("js-ctrlNext")).click();
return true;
}
} catch (NoSuchElementException e) {
return false;
}
return false;
}
public String getGrantTitle(WebElement grant) {
return grant.findElement(By.cssSelector("td.tertiary")).findElement(By.tagName("a")).getText();
}
public String getFirstDeadline(WebElement grant) {
return grant.findElement(By.xpath("./td[5]")).getText();
}
}

View File

@ -5,6 +5,9 @@ import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.text.ParseException;
@Service
public class GrantScheduler {
private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true;
@ -31,22 +34,11 @@ public class GrantScheduler {
@Scheduled(cron = "0 0 8 1 * ?", zone = "Europe/Samara")
public void loadGrantsFromKias() {
log.debug("GrantScheduler.loadGrantsFromKias started");
//
// Метод для сохранения загруженных грантов
//
// List<GrantDto> grants = IndexKiasTest.getNewGrantsDto();
// grants.forEach(grantDto -> {
// try {
// if (grantService.saveFromKias(grantDto)) {
// log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded");
// } else {
// log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists");
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// });
try {
grantService.createFromKias();
} catch (ParseException | IOException e) {
e.printStackTrace();
}
log.debug("GrantScheduler.loadGrantsFromKias finished");
}
}

View File

@ -1,6 +1,8 @@
package ru.ulstu.grant.service;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;
@ -23,6 +25,7 @@ import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService;
import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
@ -39,6 +42,7 @@ import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION;
@Service
public class GrantService extends BaseService {
private final static int MAX_DISPLAY_SIZE = 50;
private final Logger log = LoggerFactory.getLogger(GrantService.class);
private final GrantRepository grantRepository;
private final ProjectService projectService;
@ -48,6 +52,7 @@ public class GrantService extends BaseService {
private final PaperService paperService;
private final EventService eventService;
private final GrantNotificationService grantNotificationService;
private final KiasService kiasService;
public GrantService(GrantRepository grantRepository,
FileService fileService,
@ -56,8 +61,10 @@ public class GrantService extends BaseService {
UserService userService,
PaperService paperService,
EventService eventService,
GrantNotificationService grantNotificationService) {
GrantNotificationService grantNotificationService,
KiasService kiasService) {
this.grantRepository = grantRepository;
this.kiasService = kiasService;
this.baseRepository = grantRepository;
this.fileService = fileService;
this.deadlineService = deadlineService;
@ -317,4 +324,15 @@ public class GrantService extends BaseService {
.filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription()))
.collect(Collectors.toList()));
}
@Transactional
public void createFromKias() throws IOException, ParseException {
for (GrantDto grantDto : kiasService.getNewGrantsDto()) {
if (saveFromKias(grantDto)) {
log.debug("GrantScheduler.loadGrantsFromKias new grant was loaded");
} else {
log.debug("GrantScheduler.loadGrantsFromKias grant wasn't loaded, cause it's already exists");
}
}
}
}

View File

@ -0,0 +1,83 @@
package ru.ulstu.grant.service;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.stereotype.Service;
import ru.ulstu.deadline.model.Deadline;
import ru.ulstu.grant.model.Grant;
import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.grant.page.KiasPage;
import ru.ulstu.user.service.UserService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@Service
public class KiasService {
private final static String BASE_URL = "https://www.rfbr.ru/rffi/ru/contest_search?CONTEST_STATUS_ID=%s&CONTEST_TYPE=%s&CONTEST_YEAR=%s";
private final static String CONTEST_STATUS_ID = "1";
private final static String CONTEST_TYPE = "-1";
private final static int CONTEST_YEAR = Calendar.getInstance().get(Calendar.YEAR);
private final static String DRIVER_LOCATION = "drivers/%s";
private final static String WINDOWS_DRIVER = "chromedriver.exe";
private final static String LINUX_DRIVER = "chromedriver";
private final static String DRIVER_TYPE = "webdriver.chrome.driver";
private final UserService userService;
private WebDriver webDriver;
public KiasService(UserService userService) {
System.setProperty(DRIVER_TYPE, getDriverExecutablePath());
this.userService = userService;
final ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
webDriver = new ChromeDriver(chromeOptions);
}
public List<GrantDto> getNewGrantsDto() throws ParseException {
webDriver.get(String.format(BASE_URL, CONTEST_STATUS_ID, CONTEST_TYPE, CONTEST_YEAR));
KiasPage kiasPage = new KiasPage(webDriver);
List<WebElement> kiasGrants = new ArrayList<>();
List<GrantDto> newGrants = new ArrayList<>();
do {
kiasGrants.addAll(kiasPage.getPageOfGrants());
for (WebElement grant : kiasGrants) {
GrantDto grantDto = new GrantDto();
grantDto.setTitle(kiasPage.getGrantTitle(grant));
String deadlineDate = kiasPage.getFirstDeadline(grant); //10.06.2019 23:59
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
Date date = formatter.parse(deadlineDate);
Deadline deadline = new Deadline(date, "Окончание приёма заявок");
grantDto.setDeadlines(Arrays.asList(deadline));
grantDto.setLeaderId(userService.findOneByLoginIgnoreCase("admin").getId());
grantDto.setStatus(Grant.GrantStatus.LOADED_FROM_KIAS);
newGrants.add(grantDto);
}
kiasGrants.clear();
}
while (kiasPage.checkPagination()); //проверка существования следующей страницы с грантами
return newGrants;
}
private String getDriverExecutablePath() {
return KiasService.class.getClassLoader().getResource(
String.format(DRIVER_LOCATION, getDriverExecutable(isWindows()))).getFile();
}
private String getDriverExecutable(boolean isWindows) {
return isWindows ? WINDOWS_DRIVER : LINUX_DRIVER;
}
private boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("windows");
}
}

View File

@ -1,344 +1,349 @@
package ru.ulstu.user.service;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.mail.MailException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.configuration.ApplicationProperties;
import ru.ulstu.core.error.EntityIdIsNullException;
import ru.ulstu.core.jpa.OffsetablePageRequest;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.response.PageableItems;
import ru.ulstu.user.error.UserActivationError;
import ru.ulstu.user.error.UserEmailExistsException;
import ru.ulstu.user.error.UserIdExistsException;
import ru.ulstu.user.error.UserIsUndeadException;
import ru.ulstu.user.error.UserLoginExistsException;
import ru.ulstu.user.error.UserNotActivatedException;
import ru.ulstu.user.error.UserNotFoundException;
import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException;
import ru.ulstu.user.error.UserResetKeyError;
import ru.ulstu.user.error.UserSendingMailException;
import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.model.UserListDto;
import ru.ulstu.user.model.UserResetPasswordDto;
import ru.ulstu.user.model.UserRole;
import ru.ulstu.user.model.UserRoleConstants;
import ru.ulstu.user.model.UserRoleDto;
import ru.ulstu.user.repository.UserRepository;
import ru.ulstu.user.repository.UserRoleRepository;
import ru.ulstu.user.util.UserUtils;
import javax.mail.MessagingException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@Transactional
public class UserService implements UserDetailsService {
private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка";
private final Logger log = LoggerFactory.getLogger(UserService.class);
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final UserRoleRepository userRoleRepository;
private final UserMapper userMapper;
private final MailService mailService;
private final ApplicationProperties applicationProperties;
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
UserRoleRepository userRoleRepository,
UserMapper userMapper,
MailService mailService,
ApplicationProperties applicationProperties) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.userRoleRepository = userRoleRepository;
this.userMapper = userMapper;
this.mailService = mailService;
this.applicationProperties = applicationProperties;
}
private User getUserByEmail(String email) {
return userRepository.findOneByEmailIgnoreCase(email);
}
private User getUserByActivationKey(String activationKey) {
return userRepository.findOneByActivationKey(activationKey);
}
public User getUserByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
@Transactional(readOnly = true)
public UserDto getUserWithRolesById(Integer userId) {
final User userEntity = userRepository.findOneWithRolesById(userId);
if (userEntity == null) {
throw new UserNotFoundException(userId.toString());
}
return userMapper.userEntityToUserDto(userEntity);
}
@Transactional(readOnly = true)
public PageableItems<UserListDto> getAllUsers(int offset, int count) {
final Page<User> page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id")));
return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent()));
}
// TODO: read only active users
public List<User> findAll() {
return userRepository.findAll();
}
@Transactional(readOnly = true)
public PageableItems<UserRoleDto> getUserRoles() {
final List<UserRoleDto> roles = userRoleRepository.findAll().stream()
.map(UserRoleDto::new)
.sorted(Comparator.comparing(UserRoleDto::getViewValue))
.collect(Collectors.toList());
return new PageableItems<>(roles.size(), roles);
}
public UserDto createUser(UserDto userDto) {
if (userDto.getId() != null) {
throw new UserIdExistsException();
}
if (getUserByLogin(userDto.getLogin()) != null) {
throw new UserLoginExistsException(userDto.getLogin());
}
if (getUserByEmail(userDto.getEmail()) != null) {
throw new UserEmailExistsException(userDto.getEmail());
}
if (!userDto.isPasswordsValid()) {
throw new UserPasswordsNotValidOrNotMatchException("");
}
User user = userMapper.userDtoToUserEntity(userDto);
user.setActivated(false);
user.setActivationKey(UserUtils.generateActivationKey());
user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER)));
user.setPassword(passwordEncoder.encode(userDto.getPassword()));
user = userRepository.save(user);
mailService.sendActivationEmail(user);
log.debug("Created Information for User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user);
}
public UserDto activateUser(String activationKey) {
final User user = getUserByActivationKey(activationKey);
if (user == null) {
throw new UserActivationError(activationKey);
}
user.setActivated(true);
user.setActivationKey(null);
user.setActivationDate(null);
log.debug("Activated user: {}", user.getLogin());
return userMapper.userEntityToUserDto(userRepository.save(user));
}
public UserDto updateUser(UserDto userDto) {
if (userDto.getId() == null) {
throw new EntityIdIsNullException();
}
if (!Objects.equals(
Optional.ofNullable(getUserByEmail(userDto.getEmail()))
.map(BaseEntity::getId).orElse(userDto.getId()),
userDto.getId())) {
throw new UserEmailExistsException(userDto.getEmail());
}
if (!Objects.equals(
Optional.ofNullable(getUserByLogin(userDto.getLogin()))
.map(BaseEntity::getId).orElse(userDto.getId()),
userDto.getId())) {
throw new UserLoginExistsException(userDto.getLogin());
}
User user = userRepository.findOne(userDto.getId());
if (user == null) {
throw new UserNotFoundException(userDto.getId().toString());
}
if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) {
userDto.setLogin(applicationProperties.getUndeadUserLogin());
userDto.setActivated(true);
userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN)));
}
user.setLogin(userDto.getLogin());
user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName());
user.setEmail(userDto.getEmail());
if (userDto.isActivated() != user.getActivated()) {
if (userDto.isActivated()) {
user.setActivationKey(null);
user.setActivationDate(null);
} else {
user.setActivationKey(UserUtils.generateActivationKey());
user.setActivationDate(new Date());
}
}
user.setActivated(userDto.isActivated());
final Set<UserRole> roles = userMapper.rolesFromDto(userDto.getRoles());
user.setRoles(roles.isEmpty()
? Collections.singleton(new UserRole(UserRoleConstants.USER))
: roles);
if (!StringUtils.isEmpty(userDto.getOldPassword())) {
if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) {
throw new UserPasswordsNotValidOrNotMatchException("");
}
if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) {
throw new UserPasswordsNotValidOrNotMatchException("");
}
user.setPassword(passwordEncoder.encode(userDto.getPassword()));
log.debug("Changed password for User: {}", user.getLogin());
}
user = userRepository.save(user);
log.debug("Changed Information for User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user);
}
public UserDto updateUserInformation(User user, UserDto updateUser) {
user.setFirstName(updateUser.getFirstName());
user.setLastName(updateUser.getLastName());
user.setEmail(updateUser.getEmail());
user.setLogin(updateUser.getLogin());
user = userRepository.save(user);
log.debug("Updated Information for User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user);
}
public void changeUserPassword(User user, Map<String, String> payload) {
if (!payload.get("password").equals(payload.get("confirmPassword"))) {
throw new UserPasswordsNotValidOrNotMatchException("");
}
if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) {
throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно");
}
user.setPassword(passwordEncoder.encode(payload.get("password")));
log.debug("Changed password for User: {}", user.getLogin());
userRepository.save(user);
mailService.sendChangePasswordMail(user);
}
public boolean requestUserPasswordReset(String email) {
User user = userRepository.findOneByEmailIgnoreCase(email);
if (user == null) {
throw new UserNotFoundException(email);
}
if (!user.getActivated()) {
throw new UserNotActivatedException();
}
user.setResetKey(UserUtils.generateResetKey());
user.setResetDate(new Date());
user = userRepository.save(user);
mailService.sendPasswordResetMail(user);
log.debug("Created Reset Password Request for User: {}", user.getLogin());
return true;
}
public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) {
if (!userResetPasswordDto.isPasswordsValid()) {
throw new UserPasswordsNotValidOrNotMatchException("");
}
User user = userRepository.findOneByResetKey(key);
if (user == null) {
throw new UserResetKeyError(key);
}
user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword()));
user.setResetKey(null);
user.setResetDate(null);
user = userRepository.save(user);
log.debug("Reset Password for User: {}", user.getLogin());
return true;
}
public UserDto deleteUser(Integer userId) {
final User user = userRepository.findOne(userId);
if (user == null) {
throw new UserNotFoundException(userId.toString());
}
if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) {
throw new UserIsUndeadException(user.getLogin());
}
userRepository.delete(user);
log.debug("Deleted User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user);
}
@Override
public UserDetails loadUserByUsername(String username) {
final User user = userRepository.findOneByLoginIgnoreCase(username);
if (user == null) {
throw new UserNotFoundException(username);
}
if (!user.getActivated()) {
throw new UserNotActivatedException();
}
return new org.springframework.security.core.userdetails.User(user.getLogin(),
user.getPassword(),
Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList()));
}
public List<User> findByIds(List<Integer> ids) {
return userRepository.findAll(ids);
}
public User findById(Integer id) {
return userRepository.findOne(id);
}
public User getCurrentUser() {
String login = UserUtils.getCurrentUserLogin();
User user = userRepository.findOneByLoginIgnoreCase(login);
if (user == null) {
throw new UserNotFoundException(login);
}
return user;
}
public List<User> filterByAgeAndDegree(boolean hasDegree, boolean hasAge) {
return userRepository.filterByAgeAndDegree(hasDegree, hasAge);
}
public void inviteUser(String email) throws UserSendingMailException {
if (userRepository.findOneByEmailIgnoreCase(email) != null) {
throw new UserEmailExistsException(email);
}
String password = UserUtils.generatePassword();
User user = new User();
user.setPassword(passwordEncoder.encode(password));
user.setLogin(email);
user.setEmail(email);
user.setFirstName("user");
user.setLastName("user");
user.setActivated(true);
userRepository.save(user);
Map<String, Object> variables = ImmutableMap.of("password", password, "email", email);
try {
mailService.sendInviteMail(variables, email);
} catch (MessagingException | MailException e) {
throw new UserSendingMailException(email);
}
}
}
package ru.ulstu.user.service;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.mail.MailException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.configuration.ApplicationProperties;
import ru.ulstu.core.error.EntityIdIsNullException;
import ru.ulstu.core.jpa.OffsetablePageRequest;
import ru.ulstu.core.model.BaseEntity;
import ru.ulstu.core.model.response.PageableItems;
import ru.ulstu.grant.model.GrantDto;
import ru.ulstu.user.error.UserActivationError;
import ru.ulstu.user.error.UserEmailExistsException;
import ru.ulstu.user.error.UserIdExistsException;
import ru.ulstu.user.error.UserIsUndeadException;
import ru.ulstu.user.error.UserLoginExistsException;
import ru.ulstu.user.error.UserNotActivatedException;
import ru.ulstu.user.error.UserNotFoundException;
import ru.ulstu.user.error.UserPasswordsNotValidOrNotMatchException;
import ru.ulstu.user.error.UserResetKeyError;
import ru.ulstu.user.error.UserSendingMailException;
import ru.ulstu.user.model.User;
import ru.ulstu.user.model.UserDto;
import ru.ulstu.user.model.UserListDto;
import ru.ulstu.user.model.UserResetPasswordDto;
import ru.ulstu.user.model.UserRole;
import ru.ulstu.user.model.UserRoleConstants;
import ru.ulstu.user.model.UserRoleDto;
import ru.ulstu.user.repository.UserRepository;
import ru.ulstu.user.repository.UserRoleRepository;
import ru.ulstu.user.util.UserUtils;
import javax.mail.MessagingException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@Transactional
public class UserService implements UserDetailsService {
private static final String INVITE_USER_EXCEPTION = "Во время отправки приглашения произошла ошибка";
private final Logger log = LoggerFactory.getLogger(UserService.class);
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final UserRoleRepository userRoleRepository;
private final UserMapper userMapper;
private final MailService mailService;
private final ApplicationProperties applicationProperties;
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
UserRoleRepository userRoleRepository,
UserMapper userMapper,
MailService mailService,
ApplicationProperties applicationProperties) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.userRoleRepository = userRoleRepository;
this.userMapper = userMapper;
this.mailService = mailService;
this.applicationProperties = applicationProperties;
}
private User getUserByEmail(String email) {
return userRepository.findOneByEmailIgnoreCase(email);
}
private User getUserByActivationKey(String activationKey) {
return userRepository.findOneByActivationKey(activationKey);
}
public User getUserByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
@Transactional(readOnly = true)
public UserDto getUserWithRolesById(Integer userId) {
final User userEntity = userRepository.findOneWithRolesById(userId);
if (userEntity == null) {
throw new UserNotFoundException(userId.toString());
}
return userMapper.userEntityToUserDto(userEntity);
}
@Transactional(readOnly = true)
public PageableItems<UserListDto> getAllUsers(int offset, int count) {
final Page<User> page = userRepository.findAll(new OffsetablePageRequest(offset, count, new Sort("id")));
return new PageableItems<>(page.getTotalElements(), userMapper.userEntitiesToUserListDtos(page.getContent()));
}
// TODO: read only active users
public List<User> findAll() {
return userRepository.findAll();
}
@Transactional(readOnly = true)
public PageableItems<UserRoleDto> getUserRoles() {
final List<UserRoleDto> roles = userRoleRepository.findAll().stream()
.map(UserRoleDto::new)
.sorted(Comparator.comparing(UserRoleDto::getViewValue))
.collect(Collectors.toList());
return new PageableItems<>(roles.size(), roles);
}
public UserDto createUser(UserDto userDto) {
if (userDto.getId() != null) {
throw new UserIdExistsException();
}
if (getUserByLogin(userDto.getLogin()) != null) {
throw new UserLoginExistsException(userDto.getLogin());
}
if (getUserByEmail(userDto.getEmail()) != null) {
throw new UserEmailExistsException(userDto.getEmail());
}
if (!userDto.isPasswordsValid()) {
throw new UserPasswordsNotValidOrNotMatchException("");
}
User user = userMapper.userDtoToUserEntity(userDto);
user.setActivated(false);
user.setActivationKey(UserUtils.generateActivationKey());
user.setRoles(Collections.singleton(new UserRole(UserRoleConstants.USER)));
user.setPassword(passwordEncoder.encode(userDto.getPassword()));
user = userRepository.save(user);
mailService.sendActivationEmail(user);
log.debug("Created Information for User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user);
}
public UserDto activateUser(String activationKey) {
final User user = getUserByActivationKey(activationKey);
if (user == null) {
throw new UserActivationError(activationKey);
}
user.setActivated(true);
user.setActivationKey(null);
user.setActivationDate(null);
log.debug("Activated user: {}", user.getLogin());
return userMapper.userEntityToUserDto(userRepository.save(user));
}
public UserDto updateUser(UserDto userDto) {
if (userDto.getId() == null) {
throw new EntityIdIsNullException();
}
if (!Objects.equals(
Optional.ofNullable(getUserByEmail(userDto.getEmail()))
.map(BaseEntity::getId).orElse(userDto.getId()),
userDto.getId())) {
throw new UserEmailExistsException(userDto.getEmail());
}
if (!Objects.equals(
Optional.ofNullable(getUserByLogin(userDto.getLogin()))
.map(BaseEntity::getId).orElse(userDto.getId()),
userDto.getId())) {
throw new UserLoginExistsException(userDto.getLogin());
}
User user = userRepository.findOne(userDto.getId());
if (user == null) {
throw new UserNotFoundException(userDto.getId().toString());
}
if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) {
userDto.setLogin(applicationProperties.getUndeadUserLogin());
userDto.setActivated(true);
userDto.setRoles(Collections.singletonList(new UserRoleDto(UserRoleConstants.ADMIN)));
}
user.setLogin(userDto.getLogin());
user.setFirstName(userDto.getFirstName());
user.setLastName(userDto.getLastName());
user.setEmail(userDto.getEmail());
if (userDto.isActivated() != user.getActivated()) {
if (userDto.isActivated()) {
user.setActivationKey(null);
user.setActivationDate(null);
} else {
user.setActivationKey(UserUtils.generateActivationKey());
user.setActivationDate(new Date());
}
}
user.setActivated(userDto.isActivated());
final Set<UserRole> roles = userMapper.rolesFromDto(userDto.getRoles());
user.setRoles(roles.isEmpty()
? Collections.singleton(new UserRole(UserRoleConstants.USER))
: roles);
if (!StringUtils.isEmpty(userDto.getOldPassword())) {
if (!userDto.isPasswordsValid() || !userDto.isOldPasswordValid()) {
throw new UserPasswordsNotValidOrNotMatchException("");
}
if (!passwordEncoder.matches(userDto.getOldPassword(), user.getPassword())) {
throw new UserPasswordsNotValidOrNotMatchException("");
}
user.setPassword(passwordEncoder.encode(userDto.getPassword()));
log.debug("Changed password for User: {}", user.getLogin());
}
user = userRepository.save(user);
log.debug("Changed Information for User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user);
}
public UserDto updateUserInformation(User user, UserDto updateUser) {
user.setFirstName(updateUser.getFirstName());
user.setLastName(updateUser.getLastName());
user.setEmail(updateUser.getEmail());
user.setLogin(updateUser.getLogin());
user = userRepository.save(user);
log.debug("Updated Information for User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user);
}
public void changeUserPassword(User user, Map<String, String> payload) {
if (!payload.get("password").equals(payload.get("confirmPassword"))) {
throw new UserPasswordsNotValidOrNotMatchException("");
}
if (!passwordEncoder.matches(payload.get("oldPassword"), user.getPassword())) {
throw new UserPasswordsNotValidOrNotMatchException("Старый пароль введен неправильно");
}
user.setPassword(passwordEncoder.encode(payload.get("password")));
log.debug("Changed password for User: {}", user.getLogin());
userRepository.save(user);
mailService.sendChangePasswordMail(user);
}
public boolean requestUserPasswordReset(String email) {
User user = userRepository.findOneByEmailIgnoreCase(email);
if (user == null) {
throw new UserNotFoundException(email);
}
if (!user.getActivated()) {
throw new UserNotActivatedException();
}
user.setResetKey(UserUtils.generateResetKey());
user.setResetDate(new Date());
user = userRepository.save(user);
mailService.sendPasswordResetMail(user);
log.debug("Created Reset Password Request for User: {}", user.getLogin());
return true;
}
public boolean completeUserPasswordReset(String key, UserResetPasswordDto userResetPasswordDto) {
if (!userResetPasswordDto.isPasswordsValid()) {
throw new UserPasswordsNotValidOrNotMatchException("");
}
User user = userRepository.findOneByResetKey(key);
if (user == null) {
throw new UserResetKeyError(key);
}
user.setPassword(passwordEncoder.encode(userResetPasswordDto.getPassword()));
user.setResetKey(null);
user.setResetDate(null);
user = userRepository.save(user);
log.debug("Reset Password for User: {}", user.getLogin());
return true;
}
public UserDto deleteUser(Integer userId) {
final User user = userRepository.findOne(userId);
if (user == null) {
throw new UserNotFoundException(userId.toString());
}
if (applicationProperties.getUndeadUserLogin().equalsIgnoreCase(user.getLogin())) {
throw new UserIsUndeadException(user.getLogin());
}
userRepository.delete(user);
log.debug("Deleted User: {}", user.getLogin());
return userMapper.userEntityToUserDto(user);
}
@Override
public UserDetails loadUserByUsername(String username) {
final User user = userRepository.findOneByLoginIgnoreCase(username);
if (user == null) {
throw new UserNotFoundException(username);
}
if (!user.getActivated()) {
throw new UserNotActivatedException();
}
return new org.springframework.security.core.userdetails.User(user.getLogin(),
user.getPassword(),
Optional.ofNullable(user.getRoles()).orElse(Collections.emptySet()).stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList()));
}
public List<User> findByIds(List<Integer> ids) {
return userRepository.findAll(ids);
}
public User findById(Integer id) {
return userRepository.findOne(id);
}
public User getCurrentUser() {
String login = UserUtils.getCurrentUserLogin();
User user = userRepository.findOneByLoginIgnoreCase(login);
if (user == null) {
throw new UserNotFoundException(login);
}
return user;
}
public List<User> filterByAgeAndDegree(boolean hasDegree, boolean hasAge) {
return userRepository.filterByAgeAndDegree(hasDegree, hasAge);
}
public void inviteUser(String email) throws UserSendingMailException {
if (userRepository.findOneByEmailIgnoreCase(email) != null) {
throw new UserEmailExistsException(email);
}
String password = UserUtils.generatePassword();
User user = new User();
user.setPassword(passwordEncoder.encode(password));
user.setLogin(email);
user.setEmail(email);
user.setFirstName("user");
user.setLastName("user");
user.setActivated(true);
userRepository.save(user);
Map<String, Object> variables = ImmutableMap.of("password", password, "email", email);
try {
mailService.sendInviteMail(variables, email);
} catch (MessagingException | MailException e) {
throw new UserSendingMailException(email);
}
}
public User findOneByLoginIgnoreCase(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
}

0
src/main/resources/drivers/chromedriver Normal file → Executable file
View File

0
src/main/resources/drivers/geckodriver Normal file → Executable file
View File