Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cz.swi2.mendeluis.service.facade; import cz.swi2.mendeluis.dataaccesslayer.domain.User; import cz.swi2.mendeluis.dto.UserDTO; import cz.swi2.mendeluis.facade.IUserFacade; import cz.swi2.mendeluis.service.BeanMappingService; import cz.swi2.mendeluis.service.UserService; import java.security.Principal; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * Pro prci s uivatelem * * @author Roman */ @Service @Transactional public class UserFacade implements IUserFacade { @Autowired private BeanMappingService beanMappingService; @Autowired private UserService userService; @Override public UserDTO createNewUser(String name, String username, String password) { User user = userService.createNewUser(name, username, password); UserDTO newUser = beanMappingService.mapTo(user, UserDTO.class); return newUser; } @Override public UserDTO getUserByUsername(String username) { return beanMappingService.mapTo(userService.getUserByUsername(username), UserDTO.class); } @Override public UserDTO getUserByCredentials(String username, String password) { return beanMappingService.mapTo(userService.getUserByCredentials(username, password), UserDTO.class); } @Override public List<UserDTO> getAllUsers() { return beanMappingService.mapTo(userService.getAllUsers(), UserDTO.class); } @Override public void deleteUser(int id) { userService.deleteUser(id); } @Override public void doLogin(String username) { try { Authentication token = new UsernamePasswordAuthenticationToken(username, null); SecurityContextHolder.getContext().setAuthentication(token); } catch (Exception e) { SecurityContextHolder.getContext().setAuthentication(null); } } @Override public void doLogout() { SecurityContextHolder.getContext().setAuthentication(null); } @Override public UserDTO getLoggedUser() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth == null) { return null; } String username = ((org.springframework.security.core.userdetails.User) auth.getPrincipal()).getUsername(); if (username == null) { return null; } UserDTO user = this.getUserByUsername(username); if (user == null) { return null; } return user; } }