#120 move to services

pull/221/head
Anton Romanov 5 years ago
parent 457f1da985
commit c303d65c8d

@ -126,6 +126,6 @@ dependencies {
compile group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.6.0' 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.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'
} }

@ -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();
}
}

@ -5,6 +5,9 @@ import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.IOException;
import java.text.ParseException;
@Service @Service
public class GrantScheduler { public class GrantScheduler {
private final static boolean IS_DEADLINE_NOTIFICATION_BEFORE_WEEK = true; 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") @Scheduled(cron = "0 0 8 1 * ?", zone = "Europe/Samara")
public void loadGrantsFromKias() { public void loadGrantsFromKias() {
log.debug("GrantScheduler.loadGrantsFromKias started"); log.debug("GrantScheduler.loadGrantsFromKias started");
// try {
// Метод для сохранения загруженных грантов grantService.createFromKias();
// } catch (ParseException | IOException e) {
e.printStackTrace();
// 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();
// }
// });
log.debug("GrantScheduler.loadGrantsFromKias finished"); log.debug("GrantScheduler.loadGrantsFromKias finished");
} }
} }

@ -1,6 +1,8 @@
package ru.ulstu.grant.service; package ru.ulstu.grant.service;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors; import org.springframework.validation.Errors;
@ -23,6 +25,7 @@ import ru.ulstu.user.model.User;
import ru.ulstu.user.service.UserService; import ru.ulstu.user.service.UserService;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Date; import java.util.Date;
@ -39,6 +42,7 @@ import static ru.ulstu.grant.model.Grant.GrantStatus.APPLICATION;
@Service @Service
public class GrantService extends BaseService { public class GrantService extends BaseService {
private final static int MAX_DISPLAY_SIZE = 50; private final static int MAX_DISPLAY_SIZE = 50;
private final Logger log = LoggerFactory.getLogger(GrantService.class);
private final GrantRepository grantRepository; private final GrantRepository grantRepository;
private final ProjectService projectService; private final ProjectService projectService;
@ -48,6 +52,7 @@ public class GrantService extends BaseService {
private final PaperService paperService; private final PaperService paperService;
private final EventService eventService; private final EventService eventService;
private final GrantNotificationService grantNotificationService; private final GrantNotificationService grantNotificationService;
private final KiasService kiasService;
public GrantService(GrantRepository grantRepository, public GrantService(GrantRepository grantRepository,
FileService fileService, FileService fileService,
@ -56,8 +61,10 @@ public class GrantService extends BaseService {
UserService userService, UserService userService,
PaperService paperService, PaperService paperService,
EventService eventService, EventService eventService,
GrantNotificationService grantNotificationService) { GrantNotificationService grantNotificationService,
KiasService kiasService) {
this.grantRepository = grantRepository; this.grantRepository = grantRepository;
this.kiasService = kiasService;
this.baseRepository = grantRepository; this.baseRepository = grantRepository;
this.fileService = fileService; this.fileService = fileService;
this.deadlineService = deadlineService; this.deadlineService = deadlineService;
@ -317,4 +324,15 @@ public class GrantService extends BaseService {
.filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription())) .filter(dto -> dto.getDate() != null || !org.springframework.util.StringUtils.isEmpty(dto.getDescription()))
.collect(Collectors.toList())); .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");
}
}
}
} }

@ -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");
}
}

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

Loading…
Cancel
Save