<file_sep>package pl.taskmanager.model.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Column;
import javax.validation.constraints.NotBlank;
import java.time.LocalDate;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TaskDto {
    @NotBlank(message = "Title must be not blank")
    private String title;
    @NotBlank(message = "Message must be not blank")
    @Column(columnDefinition = "text")
    private String message;
//    @NotBlank
    @Column(name = "task_interval")
    private Integer interval;
}
<file_sep>DELETE FROM role;
INSERT INTO role VALUES (1,'ROLE_USER'),(2,'ROLE_ADMIN');<file_sep>package pl.taskmanager.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import pl.taskmanager.model.Project;
import pl.taskmanager.model.Task;
import pl.taskmanager.model.dto.ProjectDto;
import pl.taskmanager.model.dto.TaskDto;
import pl.taskmanager.service.ProjectService;

import java.time.LocalDate;

@RequestMapping("/rest")
@RestController
public class ProjectController {
    private ProjectService projectService;
    @Autowired
    public ProjectController(ProjectService projectService) {
        this.projectService = projectService;
    }
    @PostMapping("/project/{acronim}&{description}&{dateStart}&{dateStop}")
    public Project createNewProject(
            @PathVariable String acronim, @PathVariable String description,
            @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate dateStart,
            @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate dateStop
            ){
        return projectService.createProject(new ProjectDto(acronim, description, dateStart,dateStop));
    }
    @PutMapping("/project/update/{project_id}&{dateStop}")
    public Project changeProjectDeadline(
            @PathVariable Long project_id,
            @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate dateStop
    ){
        return projectService.updateProjectStopDate(project_id,dateStop);
    }
    @PostMapping("/task/create/{title}&{message}&{dateStart}&{interval}&{project_id}")
    public Task addTaskToProject(
            @PathVariable String title,
            @PathVariable String message,
            @PathVariable Integer interval,
            @PathVariable Long project_id){
        return projectService.createTask(new TaskDto(
                title,message,interval),project_id);
    }
    @DeleteMapping("/task/delete/{task_id}")
    public String deleteTaskById(
            @PathVariable Long task_id){
        return "Usunięto: " + projectService.removeTask(task_id);
    }
    @DeleteMapping("/project/delete/{project_id}")
    public String deleteProjectById(
            @PathVariable Long project_id){
        return "Usunięto " + projectService.removeProjectRecursively(project_id);
    }
}
<file_sep>package pl.taskmanager.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

@Component
public class AutoMailingService {
    @Autowired
    public JavaMailSender javaMailSender;

    public void sendSimpleMessage(
            String to,
            String subject,
            String message)
    {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(message);

        javaMailSender.send(simpleMailMessage);
    }
}
<file_sep>package pl.taskmanager.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pl.taskmanager.model.Comment;
import pl.taskmanager.model.Project;
import pl.taskmanager.model.Task;
import pl.taskmanager.model.User;
import pl.taskmanager.model.dto.CommentDto;
import pl.taskmanager.model.dto.ProjectDto;
import pl.taskmanager.model.dto.TaskDto;
import pl.taskmanager.model.enums.TaskStatus;
import pl.taskmanager.repository.CommentRepository;
import pl.taskmanager.repository.ProjectRepository;
import pl.taskmanager.repository.TaskRepository;

import java.util.List;
import java.time.LocalDate;
import java.util.ListIterator;
import java.util.Optional;

@Service
public class ProjectService {
    private ProjectRepository projectRepository;
    private TaskRepository taskRepository;
    private CommentRepository commentRepository;

    @Autowired
    public ProjectService(ProjectRepository projectRepository, TaskRepository taskRepository, CommentRepository commentRepository) {
        this.projectRepository = projectRepository;
        this.taskRepository = taskRepository;
        this.commentRepository = commentRepository;
    }

    // utwórz projekt
    public Project createProject(ProjectDto projectDto) {
        return projectRepository.save(
                new Project(
                        projectDto.getAcronim(),
                        projectDto.getDescription(),
                        projectDto.getDateStart(),
                        projectDto.getDateStop()));
    }

    // zmień datę końca projektu
    public Project updateProjectStopDate(Long project_id, LocalDate dateStop) {
        // pytamy o obiekt projektu po id
        Optional<Project> projectToUpdate = projectRepository.findById(project_id);
        if (projectToUpdate.isPresent()) {
            Project project = projectToUpdate.get();
            // zmieniamy deadline
            project.setDateStop(dateStop);
            // zapisujemy na tym samym obiekcie / update
            return projectRepository.save(project);
        }
        return new Project();
    }

    // dodaj nowego taska do projektu
    public Task createTask(TaskDto taskDto, Long project_id) {
        // obiekt taska z przypisaniem do projektu
        Task task = new Task(
                taskDto.getTitle(),
                taskDto.getMessage(),
                LocalDate.now(),
                taskDto.getInterval(),
                projectRepository.getOne(project_id));
        return taskRepository.save(task);
    }

    // usuń taska z projektu
    public Task removeTask(Long task_id) {
        // wyszukaj task po id
        Task deletedTask = taskRepository.getOne(task_id);
        // usuwam obiekt
        taskRepository.delete(deletedTask);
        // zwracam usunięty obiekt
        return deletedTask;
    }

    // usunięcie projektu wraz z jego taskami
    public Project removeProjectRecursively(Long project_id) {
        Project deletedProject = projectRepository.getOne(project_id);
        projectRepository.delete(deletedProject);
        return deletedProject;
    }

    // metoda zwracająca wszystkie projekty
    public List<Project> getAllProjects() {
        return projectRepository.findAll();
    }

    // metoda zwaracjąca liczbę wszystkich tasków
    public Long countTasks() {
        return taskRepository.count();
    }

    // metoda zwracająca projekt po id
    public Project getProjectById(Long project_id) {
        return projectRepository.getOne(project_id);
    }

    public Task getTaskById(Long task_id) {
        return taskRepository.getOne(task_id);
    }

    public void addUserToTask(User user, Long task_id) {
        // wydobycie obiektu taska po id
        Task task = taskRepository.getOne(task_id);
        // dodanie obiektu User do listy users w Task
        List<User> users = task.getUsers();
        users.add(user);
        task.setUsers(users);
        // update taska
        taskRepository.save(task);
    }

    public void deleteUserFromTaskUsersList(User user, Task task) {
        List<User> users = task.getUsers();
        users.remove(user);
        task.setUsers(users);
        taskRepository.save(task);
    }

    public void updateTaskStatusAndInterval(Long task_id, Integer interval, TaskStatus taskStatus) {
        Task task = taskRepository.getOne(task_id);
        task.setInterval(interval);
        task.setTaskStatus(taskStatus);
        taskRepository.save(task);
    }

    public List<Comment> getAllCommentsByTaskId(Long task_id) {
        return commentRepository.findAllByTask(taskRepository.getOne(task_id));
    }

    public void createComment(CommentDto commentDto, Task task, String owner) {
        Comment comment = new Comment();
        comment.setContent(commentDto.getContent());
        comment.setTask(task);
        comment.setOwner(owner);
        commentRepository.save(comment);
    }

    public Integer percentOfClosedTasks() {
        Integer noClosed = taskRepository.countAllByTaskStatus(TaskStatus.CLOSED);
        Integer noAll = Math.toIntExact(taskRepository.count());
        System.out.println("CLOSED: " + noClosed);
        System.out.println("ALL: " + noAll);
        try {
            Integer result = 100 * noClosed / noAll;
            return result;
        } catch (ArithmeticException e) {
            return 0;
        }

    }

    public Integer percentOfClosedTasksInProject(Long project_id) {
        Project project = projectRepository.getOne(project_id);
        List<Task> tasks = project.getTasks();
        Integer noAll = tasks.size();
        Integer noClosed = 0;
        for (Task task : tasks) {
            if (task.getTaskStatus() == TaskStatus.CLOSED) {
                noClosed++;
            }
        }
        System.out.println("CLOSED: " + noClosed);
        System.out.println("ALL: " + noAll);
        try {
            Integer result = 100 * noClosed / noAll;
            return result;
        } catch (ArithmeticException e) {
            return 0;
        }
    }
    public Integer countAllComments(){
        return (int) commentRepository.count();
    }
    public Integer countCommentsInProject(Long project_id){
        List<Task> tasks = taskRepository.findAllByProject(projectRepository.getOne(project_id));
        Integer no_comments = 0;
        for (Task task : tasks) {
            no_comments += countCommentsInTask(task.getTask_id());
        }
        return no_comments;
    }
    public Integer countCommentsInTask(Long task_id){
        return commentRepository
                .findAllByTask(taskRepository.getOne(task_id)).size();
    }
    public List<Task> getTasksInProject(Long project_id){
        return taskRepository.findAllByProject(projectRepository.getOne(project_id));
    }

}
<file_sep>package pl.taskmanager.model.dto;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import pl.taskmanager.model.User;

import javax.validation.constraints.NotBlank;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ContactDto {
    @NotBlank
    private String content;
//    @NotBlank
    private String emailTo;
}
<file_sep>package pl.taskmanager.controller.frontEndControllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import pl.taskmanager.model.dto.UserDto;
import pl.taskmanager.service.UserService;

import javax.validation.Valid;
import java.security.NoSuchAlgorithmException;

@Controller
public class UserControllerFrontEnd {

    UserService userService;
    @Autowired
    public UserControllerFrontEnd(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/registrationConfirmed/{registration_hash}")
    public String registrationConfirmed(
            @PathVariable String registration_hash
    ){
        System.out.println("hash: " + registration_hash);
        userService.confirmedRegistration(registration_hash);
       return "redirect:/login";
    }

    @GetMapping("/register")
    public String register(Model model){
        model.addAttribute("userDto",new UserDto());
        model.addAttribute("password_repeat", "");
        return "register";
    }
    @PostMapping("/register")
    public String register(
            @ModelAttribute @Valid UserDto userDto,
            BindingResult bindingResult,
            @ModelAttribute String password_repeat,
            Model model
    ) throws NoSuchAlgorithmException {
        // błędy formularza
        if (bindingResult.hasErrors()){
            return "register";
        }
        // porwnanie haseł
        if (!userDto.getPassword().equals(userDto.getPassword_repeat())){
            System.out.println(userDto.getPassword());
            System.out.println(userDto.getPassword_repeat());
            model.addAttribute("password_error", "different passwords!");
            return "register";
        }
        // rejestracja
        userService.addUser(userDto);
        return "redirect:/projects";
    }


}
<file_sep>package pl.taskmanager.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;

@Entity
@Table(name = "employee")
@Data                   // gettery i settery
@AllArgsConstructor     // konstruktor z wsztystkimi agrumentami
@NoArgsConstructor      // konstruktor domyślny
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long employee_id;
    // dane wprowadzane przez użytkownika
    @NotBlank                        // NN
    private String name;
    @NotBlank
    private String lastname;
    @Email
    @NotBlank
    private String email;
    @NotBlank
    @Size(min = 6)
//    @Pattern(regexp = "[A-Z]{1,}")
    private String password;
    // konstruktor do rejestracji użytkownika
    public User(@NotBlank String name, @NotBlank String lastname, @Email @NotBlank String email, @NotBlank @Size(min = 6) @Pattern(regexp = "[A-Z]{1,}") String password) {
        this.name = name;
        this.lastname = lastname;
        this.email = email;
        this.password = <PASSWORD>;
    }
    // dane generowane automatycznie
    private LocalDateTime registration_datetime = LocalDateTime.now();
    private Boolean isActivated = false;
    private String confirmation;


    // realacja n:m user to role
    @ManyToMany
    @JoinTable(     // adnotacja złączająca tabele na posdstawie id
            name = "employee_role",
            joinColumns = @JoinColumn(name = "employee_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id")
    )
    @JsonIgnore
    private Set<Role> roles = new HashSet<>();
    // metoda do dodawania roli
    public void addRole(Role role){
        this.roles.add(role);
    }




}
<file_sep>package pl.taskmanager.controller.frontEndControllers;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ErrorControllerFrontEnd implements ErrorController {
    @Override
    public String getErrorPath() {
        return "/error";
    }
    @GetMapping("/error")
    public String errorPage(){
        return "404";
    }
    @GetMapping("loginError")
    public String loginError(){
        return "loginError";
    }
}
<file_sep>package pl.taskmanager.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import pl.taskmanager.model.Role;
import pl.taskmanager.model.User;
import pl.taskmanager.model.dto.UserDto;
import pl.taskmanager.repository.RoleRepository;
import pl.taskmanager.repository.UserRepository;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

@Service
public class UserService {
    private UserRepository userRepository;
    private RoleRepository roleRepository;
    private AutoMailingService autoMailingService;
    @Autowired
    public UserService(UserRepository userRepository, RoleRepository roleRepository, AutoMailingService autoMailingService) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
        this.autoMailingService = autoMailingService;
    }

    // wypisz wszystkich użytkowników
    public List<User> getAllUsers(){
        return userRepository.findAll();
    }

    @Autowired
    private PasswordEncoder passwordEncoder;

    // rejestracja użytkownika
    public User addUser(UserDto user) throws NoSuchAlgorithmException {
        // utwórz obiekt User
        User registered_user = new User(
                user.getName(),
                user.getLastname(),
                user.getEmail(),
                passwordEncoder.encode(user.getPassword())); // zwraca hash hasła
        registered_user.addRole(roleRepository.getOne(1L));
        // /registrationConfirm/email=x
        // /registrationConfirm/dsadef##!@#!@$!
        registered_user.setConfirmation(shaEncoder("email="+user.getEmail()));
        // link z potwierdzeniem
        autoMailingService.sendSimpleMessage(
                user.getEmail(),
                "TASK MANAGER: confirm your registration",
                "https://taskmanagerpub.herokuapp.com/registrationConfirmed/"+shaEncoder("email="+user.getEmail())
        );
        return userRepository.save(registered_user);
    }
    public String shaEncoder(String text) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] encodedhash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
        String hash = "";
        for (byte b : encodedhash) {
            hash += b;
        }
        return hash.replaceAll("-","");
    }

    public void confirmedRegistration(String registration_hash){
        User user = userRepository.findFirstByConfirmation(registration_hash);
        if(user != null){
            System.out.println("POTWIERDZONE");
            user.setIsActivated(true);
            userRepository.save(user);
        }else{
            System.out.println("NIC");
        }

    }

    // logowanie użytkownika
    public String loginUser(String email, String password){
        User user = userRepository.findFirstByEmailAndPassword(email,password);
        if(user == null){
            return "błąd logowania";
        }
        return "zarejestrowano: " + user.toString();
    }
    // metoda zwracająca obiekt roli po id roli
    public Role getRoleById(Long id){
        return roleRepository.getOne(id);
    }
    // metoda pobierająca Usera po adresie email
    public User getUserByEmail(String email){
        return userRepository.findFirstByEmail(email);
    }
    public User getUserById(Long user_id){
        return userRepository.getOne(user_id);
    }

}
<file_sep>package pl.taskmanager.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.taskmanager.model.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    User findFirstByEmailAndPassword(String email, String password);
    User findFirstByEmail(String email);
    User findFirstByConfirmation(String registration_confirm);
}
<file_sep>package pl.taskmanager.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import pl.taskmanager.model.Project;

@Repository
public interface ProjectRepository extends JpaRepository<Project,Long> {
}
