Ignore:
Timestamp:
02/04/22 23:22:13 (3 years ago)
Author:
Test <matonikolov77@…>
Branches:
main
Children:
5b447b0
Parents:
3ded84d
Message:

Added CRUD for movies,persons,discussion,replies,genres
Added ajaxcalls

Location:
src/main/java/com/wediscussmovies/project
Files:
2 added
3 deleted
22 edited

Legend:

Unmodified
Added
Removed
  • src/main/java/com/wediscussmovies/project/WeDiscussMoviesApplication.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project;
    22
    3 import org.springframework.beans.factory.annotation.Autowired;
    4 import org.springframework.boot.CommandLineRunner;
     3
    54import org.springframework.boot.SpringApplication;
    65import org.springframework.boot.autoconfigure.SpringBootApplication;
    7 import org.springframework.jdbc.core.JdbcTemplate;
     6import org.springframework.context.annotation.Bean;
     7import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
     8import org.springframework.security.crypto.password.PasswordEncoder;
    89
    910@SpringBootApplication
     
    1415        SpringApplication.run(WeDiscussMoviesApplication.class, args);
    1516    }
     17    @Bean
     18    PasswordEncoder getPasswordEncoder(){
     19        return new BCryptPasswordEncoder(10);
     20    }
    1621
    1722
  • src/main/java/com/wediscussmovies/project/repository/DiscussionRepository.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.repository;
    22
     3import com.wediscussmovies.project.model.Discussion;
     4import com.wediscussmovies.project.model.Movie;
     5import com.wediscussmovies.project.model.Person;
    36import org.springframework.data.jpa.repository.JpaRepository;
    47import org.springframework.stereotype.Repository;
    58
    69import java.util.List;
    7 import com.wediscussmovies.project.model.*;
    810
    911@Repository
    1012public interface DiscussionRepository extends JpaRepository<Discussion, Integer> {
    11     public List<Discussion> findAllByTitleLike(String title);
     13     List<Discussion> findAllByTitleLike(String title);
     14     List<Discussion> findAllByMovie(Movie movie);
     15     List<Discussion> findAllByPerson (Person person);
    1216}
  • src/main/java/com/wediscussmovies/project/repository/GenreRepository.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.repository;
    22
    3 import com.wediscussmovies.project.model.*;
     3import com.wediscussmovies.project.model.Genre;
     4import com.wediscussmovies.project.querymodels.GenreLikes;
    45import org.springframework.data.jpa.repository.JpaRepository;
     6import org.springframework.data.jpa.repository.Query;
    57import org.springframework.stereotype.Repository;
    68
     9import javax.transaction.Transactional;
    710import java.util.List;
    811
    912@Repository
    1013public interface GenreRepository extends JpaRepository<Genre, Integer> {
    11     public List<Genre> findAllByGenreType(String genre);
     14     List<Genre> findAllByGenreType(String genre);
     15
     16     @Query(value = "select new com.wediscussmovies.project.querymodels.GenreLikes(g.genreType, count(ug.id.userId)) from Genre g" +
     17             " left join UserGenres ug on ug.id.genreId = g.genreId" +
     18             " group by g.genreType" +
     19             " order by count(ug.id.userId) desc")
     20     @Transactional
     21     List<GenreLikes> findAllWithLikes();
    1222}
  • src/main/java/com/wediscussmovies/project/repository/MovieRepository.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.repository;
    22
     3import com.wediscussmovies.project.model.Movie;
     4import com.wediscussmovies.project.model.Person;
    35import org.springframework.data.jpa.repository.JpaRepository;
    46import org.springframework.stereotype.Repository;
    57
    68import java.util.List;
    7 import com.wediscussmovies.project.model.*;
    89
    910@Repository
    1011public interface MovieRepository extends JpaRepository<Movie, Integer> {
    11     public List<Movie> findAllByTitleLike(String Title);
     12     List<Movie> findAllByTitleLike(String Title);
     13     List<Movie> findAllByDirector(Person director);
     14     List<Movie> findAllByDirectorIsNull();
    1215}
  • src/main/java/com/wediscussmovies/project/repository/PersonRepository.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.repository;
    22
    3 import com.wediscussmovies.project.model.*;
    4 import com.wediscussmovies.project.model.enumerations.PersonType;
     3import com.wediscussmovies.project.model.Person;
    54import org.springframework.data.jpa.repository.JpaRepository;
    65import org.springframework.stereotype.Repository;
    76
    87import java.util.List;
    9 import java.util.Optional;
    108
    119@Repository
    1210public interface PersonRepository extends JpaRepository<Person, Integer> {
    13     public List<Person> findAllByType(Character type);
    14     public List<Person> findAllByTypeAndNameLike(Character type, String name);
    15     public List<Person> findAllByTypeAndSurnameLike(Character type, String surname);
    16     public Optional<Person> findPersonByPersonIdAndType(Integer id, Character type);
     11     List<Person> findAllByType(Character type);
     12     List<Person> findAllByTypeAndNameLike(Character type, String name);
     13     List<Person> findAllByTypeAndSurnameLike(Character type, String surname);
     14    // Optional<Person> findPersonByPersonIdAndType(Integer id, Character type);
     15     List<Person> findAllByTypeAndNameLikeOrSurnameLike(Character type,String name, String surname);
    1716}
  • src/main/java/com/wediscussmovies/project/repository/ReplyRepository.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.repository;
    22
     3import com.wediscussmovies.project.model.Discussion;
     4import com.wediscussmovies.project.model.Reply;
     5import com.wediscussmovies.project.model.primarykeys.ReplyPK;
    36import org.springframework.data.jpa.repository.JpaRepository;
     7import org.springframework.data.jpa.repository.Modifying;
     8import org.springframework.data.jpa.repository.Query;
     9import org.springframework.data.repository.query.Param;
    410import org.springframework.stereotype.Repository;
    5 import com.wediscussmovies.project.model.*;
     11
     12import javax.transaction.Transactional;
     13import java.sql.Date;
     14import java.util.List;
    615
    716
    817@Repository
    9 public interface ReplyRepository extends JpaRepository<Reply, Integer> {
     18public interface ReplyRepository extends JpaRepository<Reply, ReplyPK> {
     19    List<Reply> findAllByDiscussion(Discussion discussion);
     20
     21    @Modifying
     22    @Query(value = "insert into project.replies (text,date,user_id,discussion_id) values(:text,:date,:user_id,:discussion_id)",nativeQuery = true)
     23    @Transactional
     24    void insertInto(@Param("text") String text, @Param("date")Date date,
     25                    @Param("user_id")Integer userId,@Param("discussion_id")Integer discussionId);
    1026}
  • src/main/java/com/wediscussmovies/project/repository/UserRepository.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.repository;
    22
    3 import com.wediscussmovies.project.model.*;
     3import com.wediscussmovies.project.model.User;
    44import org.springframework.data.jpa.repository.JpaRepository;
    55import org.springframework.stereotype.Repository;
     
    99@Repository
    1010public interface UserRepository extends JpaRepository<User, Integer> {
    11     public Optional<User> findByEmailAndPassword(String email, String password);
    12     public Optional<User> findByUsernameAndPassword(String email, String password);
    13     public Optional<User> findByUsername(String username);
    14     public Optional<User> findByEmail(String email);
     11     Optional<User> findByUsername(String username);
    1512}
  • src/main/java/com/wediscussmovies/project/service/DiscussionService.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.service;
    22
    3 import com.wediscussmovies.project.model.*;
     3import com.wediscussmovies.project.model.Discussion;
     4import com.wediscussmovies.project.model.User;
    45
    56import java.util.List;
    6 import java.util.Optional;
    77
    88public interface DiscussionService {
    99    List<Discussion> listAll();
    1010    List<Discussion> listAllByTitle(String title);
    11     Optional<Discussion> findById(Integer id);
    12     void save(Discussion discussion);
     11    Discussion findById(Integer id);
     12    void save(Character type,Integer id, String title, String text, User user);
     13    void edit(Integer discussionId,Character type,Integer id, String title, String text);
     14    void deleteById(Integer discussionId);
     15    void likeDiscussion(Integer discussionId,Integer userId);
     16    void unlikeDiscussion(Integer discussionId,Integer userId);
     17    List<Discussion> findAllForPersonOrMovie(Integer id,Character type);
    1318}
  • src/main/java/com/wediscussmovies/project/service/GenreService.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.service;
    22
    3 import com.wediscussmovies.project.model.*;
     3import com.wediscussmovies.project.model.Genre;
     4import com.wediscussmovies.project.querymodels.GenreLikes;
    45import org.springframework.stereotype.Service;
    56
    67import java.util.List;
    7 import java.util.Optional;
    88
    99@Service
    1010public interface GenreService {
    11     public List<Genre> findAll();
    12     public Optional<Genre> findById(Integer id);
    13     public List<Genre> findAllByType(String genre);
    14     public Genre save(String genreName);
     11    List<Genre> findAll();
     12    Genre findById(Integer id);
     13    List<Genre> findAllByType(String genre);
     14    Genre save(String genreName);
     15    List<GenreLikes> findAllWithLikes();
     16
    1517}
  • src/main/java/com/wediscussmovies/project/service/MovieService.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.service;
    22
    3 import com.wediscussmovies.project.model.*;
     3import com.wediscussmovies.project.ajaxmodels.Grade;
     4import com.wediscussmovies.project.model.Genre;
     5import com.wediscussmovies.project.model.Movie;
     6import com.wediscussmovies.project.model.Person;
     7import com.wediscussmovies.project.model.User;
    48
     9import java.sql.Date;
    510import java.util.List;
    6 import java.util.Optional;
    711
    812public interface MovieService {
    9     public List<Movie> listAll();
    10     public List<Movie> searchByTitle(String title);
    11     public Optional<Movie> findById(Integer id);
    12     public Movie save(Movie movie);
    13     public void deleteById(Integer id);
     13     List<Movie> listAll();
     14     List<Movie> listAllByType(Character type);
     15     List<Movie> listAllWithoutDirector();
     16     List<Movie> searchByTitle(String title);
     17     Movie findById(Integer id);
     18     Movie save(String title, String description, String imageUrl, Date airingDate,Double  rating,
     19                Integer directorId,List<Integer> actorIds,List<Integer> genreIds);
     20
     21     Movie edit(Integer movieId,String title, String description, String imageUrl, Date airingDate,Double  rating,
     22                Integer directorId,List<Integer> actorIds, List<Integer> genreIds);
     23
     24     List<Person> findAllActorsForMovie(Movie movie);
     25     List<Genre> findAllGenresForMovie(Movie movie);
     26
     27     void likeMovie(Integer movieId, Integer userId);
     28     void unlikeMovie(Integer movieId,Integer userId);
     29
     30     List<Movie> findLikedMoviesByUser(User user);
     31
     32     void deleteById(Integer id);
     33
     34     void addGradeMovie(Integer movieId, User user, Grade grade);
    1435}
  • src/main/java/com/wediscussmovies/project/service/PersonService.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.service;
    22
    3 import com.wediscussmovies.project.model.*;
     3import com.wediscussmovies.project.ajaxmodels.Grade;
     4import com.wediscussmovies.project.model.Movie;
     5import com.wediscussmovies.project.model.Person;
     6import com.wediscussmovies.project.model.User;
    47
     8import java.sql.Date;
    59import java.util.List;
    6 import java.util.Optional;
    710
    811public interface PersonService {
     12    List<Person> findAll();
    913     List<Person> findAllDirectors();
    1014     List<Person> findAllActors();
    11     Optional<Person> findById(Integer person_id);
    12     Optional<Person> findActorById(Integer id);
    13     Optional<Person> findDirectorById(Integer id);
    14     boolean save(Person person);
    15     List<Person> findActorsByNameLike(String name);
    16     List<Person> findActorsBySurnameLike(String surname);
    17     List<Person> findDirectorsByNameLike(String name);
    18     List<Person> findDirectorsBySurnameLike(String surname);
     15    Person findById(Integer person_id);
     16
     17    Person  save(String name, String surname, Character type,
     18                 Date birthDate, String image_url, String description, List<Integer> movieIds);
     19
     20    Person edit(Integer personId, String name, String surname, Character type,
     21                Date birthDate, String image_url, String description, List<Integer> movieIds);
     22
     23    List<Person> findPersonsByNameOrSurname(Character type,String searchQuery);
     24
     25    List<Movie> findAllMoviesByPerson(Person person);
     26
     27    void deleteById(Integer id);
     28    void addGradePerson(Integer personId, User user, Grade grade);
    1929
    2030}
  • src/main/java/com/wediscussmovies/project/service/ReplyService.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.service;
    22
     3import com.wediscussmovies.project.model.Discussion;
    34import com.wediscussmovies.project.model.Reply;
     5import com.wediscussmovies.project.model.User;
     6import com.wediscussmovies.project.model.primarykeys.ReplyPK;
    47
    5 import java.util.Optional;
     8import java.util.List;
    69
    710public interface ReplyService {
    8     public Reply save(Reply r);
    9     public void delete(Reply r);
    10     Optional<Reply> findById(Long id);
     11    Reply edit(Integer replyId, Integer discussionId, String text);
     12    void delete(Integer discussionId,Integer replyId);
     13    Reply findById(Integer discussionId, Integer replyId);
     14    void save(Integer discussionId, String text, User user);
     15    void likeReply(Integer replyId,Integer userId);
     16    void unlikeReply(Integer replyId,Integer userId);
     17    List<Reply> findAllByDiscussion(Discussion discussion);
     18
     19
    1120
    1221}
  • src/main/java/com/wediscussmovies/project/service/UserService.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.service;
    22
    3 import com.wediscussmovies.project.model.*;
     3import com.wediscussmovies.project.model.User;
     4import org.springframework.security.core.userdetails.UserDetailsService;
    45
    56import javax.servlet.http.HttpServletRequest;
    67import java.util.Optional;
    78
    8 public interface UserService {
    9     public Optional<User> login(String email, String password);
    10     public Optional<User> register(HttpServletRequest request, String email, String password, String confirmPassword, String username, String name, String surname);
     9public interface UserService extends UserDetailsService {
     10     User findByUsername(String username);
     11     User register(String email, String username, String password, String confirmPassword, String name, String surname);
    1112}
  • src/main/java/com/wediscussmovies/project/service/impl/DiscussionServiceImpl.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.service.impl;
    22
    3 import com.wediscussmovies.project.model.*;
     3import com.wediscussmovies.project.model.exception.DiscussionNotExistException;
     4import com.wediscussmovies.project.model.exception.MovieIdNotFoundException;
     5import com.wediscussmovies.project.model.exception.PersonNotExistException;
     6import com.wediscussmovies.project.model.exception.UserNotExistException;
    47import com.wediscussmovies.project.repository.DiscussionRepository;
     8import com.wediscussmovies.project.model.Discussion;
     9import com.wediscussmovies.project.model.Movie;
     10import com.wediscussmovies.project.model.Person;
     11import com.wediscussmovies.project.model.User;
     12import com.wediscussmovies.project.repository.MovieRepository;
     13import com.wediscussmovies.project.repository.PersonRepository;
     14import com.wediscussmovies.project.repository.UserRepository;
    515import com.wediscussmovies.project.service.DiscussionService;
     16import com.wediscussmovies.project.service.MovieService;
     17import com.wediscussmovies.project.service.PersonService;
     18import com.wediscussmovies.project.service.UserService;
    619import org.springframework.stereotype.Service;
    720
     21import java.sql.Date;
     22import java.time.LocalDate;
    823import java.util.List;
    9 import java.util.Optional;
    1024
    1125@Service
    1226public class DiscussionServiceImpl implements DiscussionService {
     27
    1328    private final DiscussionRepository discussionRepository;
     29    private final UserRepository userRepository;
    1430
    15     public DiscussionServiceImpl(DiscussionRepository discussionRepository) {
     31    private final MovieRepository movieRepository;
     32    private final PersonRepository personRepository;
     33
     34    public DiscussionServiceImpl(DiscussionRepository discussionRepository, UserRepository userRepository,
     35                                 MovieRepository movieRepository, PersonRepository personRepository) {
    1636        this.discussionRepository = discussionRepository;
     37        this.userRepository = userRepository;
     38        this.movieRepository = movieRepository;
     39        this.personRepository = personRepository;
     40    }
     41
     42
     43
     44
     45    @Override
     46    public List<Discussion> listAll() {
     47        return this.discussionRepository.findAll();
    1748    }
    1849
    1950    @Override
    20     public List<Discussion> listAll() {
    21         return discussionRepository.findAll();
    22     }
     51    public void save(Character type,Integer id,String title, String text,User user) {
     52        Date date = Date.valueOf(LocalDate.now());
     53        Discussion discussion;
    2354
    24     @Override
    25     public void save(Discussion discussion) {
     55        if (type.equals('M')) {
     56            discussion = new Discussion('M',text,title,date,user);
     57            this.addMovieForDiscussion(id,discussion);
     58        }
     59        else{
     60            discussion = new Discussion('P',text,title,date,user);
     61            this.addPersonForDiscussion(id,discussion);
     62        }
     63
     64
     65
    2666        discussionRepository.save(discussion);
    2767    }
    2868
    2969    @Override
    30     public Optional<Discussion> findById(Integer id) {
    31         return discussionRepository.findById(id);
     70    public void edit(Integer discussionId, Character type, Integer id, String title, String text) {
     71        Discussion discussion = this.findById(discussionId);
     72
     73        discussion.setText(text);
     74        discussion.setTitle(title);
     75        discussion.setType(type);
     76        discussion.setMovie(null);
     77        discussion.setPerson(null);
     78
     79        if (type.equals('M')) {
     80            this.addMovieForDiscussion(id,discussion);
     81        }
     82        else{
     83          this.addPersonForDiscussion(id,discussion);
     84        }
     85        this.discussionRepository.save(discussion);
     86
     87    }
     88
     89    @Override
     90    public void deleteById(Integer discussionId) {
     91        this.discussionRepository.deleteById(discussionId);
     92    }
     93
     94    @Override
     95    public void likeDiscussion(Integer discussionId, Integer userId) {
     96        //ova fali od dijagram
     97    }
     98
     99    @Override
     100    public void unlikeDiscussion(Integer discussionId, Integer userId) {
     101        // ova fali od dijagram
     102    }
     103
     104    @Override
     105    public List<Discussion> findAllForPersonOrMovie(Integer id,Character type) {
     106        if (type.equals('M'))
     107        {
     108            Movie movie = this.findMovieById(id);
     109            return this.discussionRepository.findAllByMovie(movie);
     110        }
     111        Person person  = this.findPersonById(id);
     112        return this.discussionRepository.findAllByPerson(person);
     113
     114    }
     115
     116    @Override
     117    public Discussion findById(Integer id) {
     118        return discussionRepository.findById(id).orElseThrow(() -> new DiscussionNotExistException(id));
    32119    }
    33120
    34121    @Override
    35122    public List<Discussion> listAllByTitle(String title) {
     123        if(title == null || title.isEmpty())
     124         return this.listAll();
    36125        return discussionRepository.findAllByTitleLike("%"+title+"%");
    37126    }
     127    private void addMovieForDiscussion(Integer id,Discussion discussion){
     128        Movie movie = findMovieById(id);
     129        discussion.setMovie(movie);
     130
     131    }
     132
     133    private void addPersonForDiscussion(Integer id, Discussion discussion){
     134        Person person = findPersonById(id);
     135        discussion.setPerson(person);
     136
     137    }
     138    private Movie findMovieById(Integer id){
     139        return this.movieRepository.findById(id).orElseThrow(() -> new MovieIdNotFoundException(id));
     140    }
     141    private Person findPersonById(Integer id){
     142        return this.personRepository.findById(id).orElseThrow(() -> new PersonNotExistException(id));
     143
     144    }
    38145}
  • src/main/java/com/wediscussmovies/project/service/impl/GenreServiceImpl.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.service.impl;
    22
    3 import com.wediscussmovies.project.model.*;
     3import com.wediscussmovies.project.model.exception.GenreNotExistException;
     4import com.wediscussmovies.project.querymodels.GenreLikes;
    45import com.wediscussmovies.project.repository.GenreRepository;
     6import com.wediscussmovies.project.model.Genre;
    57import com.wediscussmovies.project.service.GenreService;
    68import org.springframework.stereotype.Service;
    79
    810import java.util.List;
    9 import java.util.Optional;
    1011
    1112@Service
     
    1819
    1920    @Override
    20     public Optional<Genre> findById(Integer id) {
    21         return genreRepository.findById(id);
     21    public Genre findById(Integer id) {
     22        return this.genreRepository.findById(id).orElseThrow(() -> new GenreNotExistException(id));
    2223    }
    2324
    2425    @Override
    2526    public List<Genre> findAllByType(String genre) {
    26         return genreRepository.findAllByGenreType(genre);
     27        return this.genreRepository.findAllByGenreType(genre);
    2728    }
    2829
     
    3031    public Genre save(String genreName) {
    3132       Genre genre = new Genre(genreName);
    32         return genreRepository.save(genre);
     33        return this.genreRepository.save(genre);
     34    }
     35
     36    @Override
     37    public List<GenreLikes> findAllWithLikes() {
     38        return this.genreRepository.findAllWithLikes();
    3339    }
    3440
    3541    @Override
    3642    public List<Genre> findAll() {
    37         return genreRepository.findAll();
     43        return this.genreRepository.findAll();
    3844    }
    3945}
  • src/main/java/com/wediscussmovies/project/service/impl/MovieServiceImpl.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.service.impl;
    22
     3
     4import com.wediscussmovies.project.ajaxmodels.Grade;
    35import com.wediscussmovies.project.model.*;
    4 import com.wediscussmovies.project.repository.MovieRepository;
     6import com.wediscussmovies.project.model.exception.GenreNotExistException;
     7import com.wediscussmovies.project.model.exception.PersonNotExistException;
     8import com.wediscussmovies.project.model.exception.UserNotExistException;
     9import com.wediscussmovies.project.model.primarykeys.MovieLikesPK;
     10import com.wediscussmovies.project.model.primarykeys.MovieRatesPK;
     11import com.wediscussmovies.project.model.relation.MovieActors;
     12import com.wediscussmovies.project.model.relation.MovieGenres;
     13import com.wediscussmovies.project.model.relation.MovieLikes;
     14import com.wediscussmovies.project.model.relation.MovieRates;
     15import com.wediscussmovies.project.repository.*;
     16import com.wediscussmovies.project.model.exception.MovieIdNotFoundException;
    517import com.wediscussmovies.project.service.MovieService;
    618import org.springframework.stereotype.Service;
    719
     20import javax.swing.text.html.Option;
     21import javax.transaction.Transactional;
     22import java.sql.Date;
    823import java.util.List;
    924import java.util.Optional;
     25import java.util.stream.Collectors;
    1026
    1127@Service
    1228public class MovieServiceImpl implements MovieService {
     29
    1330    private final MovieRepository movieRepository;
    14 
    15     public MovieServiceImpl(MovieRepository movieRepository) {
     31    private final PersonRepository personRepository;
     32    private final GenreRepository genreRepository;
     33    private final MovieActorsRepository movieActorsRepository;
     34    private final MovieGenresRepository movieGenresRepository;
     35    private final UserRepository userRepository;
     36    private final MovieLikesRepository movieLikesRepository;
     37    private final MovieRatesRepository movieRatesRepository;
     38
     39    public MovieServiceImpl(MovieRepository movieRepository, PersonRepository personRepository,
     40                            GenreRepository genreRepository, MovieActorsRepository movieActorsRepository,
     41                            MovieGenresRepository movieGenresRepository,
     42                            UserRepository userRepository, MovieLikesRepository movieLikesRepository,
     43                            MovieRatesRepository movieRatesRepository) {
     44
    1645        this.movieRepository = movieRepository;
     46        this.personRepository = personRepository;
     47        this.genreRepository = genreRepository;
     48        this.movieActorsRepository = movieActorsRepository;
     49        this.movieGenresRepository = movieGenresRepository;
     50        this.userRepository = userRepository;
     51        this.movieLikesRepository = movieLikesRepository;
     52        this.movieRatesRepository = movieRatesRepository;
    1753    }
    1854
    1955    @Override
    2056    public List<Movie> listAll() {
    21         return movieRepository.findAll();
    22     }
    23 
    24     @Override
    25     public Optional<Movie> findById(Integer id) {
    26         return movieRepository.findById(1);
    27     }
    28 
    29     @Override
    30     public Movie save(Movie movie) {
    31         return movieRepository.save(movie);
    32     }
     57        return this.movieRepository.findAll();
     58    }
     59
     60    @Override
     61    public List<Movie> listAllByType(Character type) {
     62        if (type.equals('A'))
     63            return this.listAll();
     64        return this.listAllWithoutDirector();
     65    }
     66
     67    @Override
     68    public List<Movie> listAllWithoutDirector() {
     69        return this.movieRepository.findAllByDirectorIsNull();
     70    }
     71
     72    @Override
     73    public Movie findById(Integer id) {
     74        return this.movieRepository.findById(id).orElseThrow(() -> new MovieIdNotFoundException(id));
     75    }
     76
     77    @Override
     78    @Transactional
     79    public Movie save(String title, String description, String imageUrl,
     80                      Date airingDate, Double rating, Integer directorId,List<Integer> actorIds,List<Integer> genreIds) {
     81
     82
     83        Person director =getDirector(directorId);
     84        Movie movie = new Movie(title,description,imageUrl,airingDate,rating,director);
     85       movie = this.movieRepository.saveAndFlush(movie);
     86       addActorsAndGenresForMovie(movie,actorIds,genreIds);
     87       return movie;
     88    }
     89
     90
     91    @Transactional
     92    @Override
     93    public Movie edit(Integer movieId, String title, String description,
     94                      String imageUrl, Date airingDate, Double rating,
     95                      Integer directorId, List<Integer> actorIds,List<Integer> genreIds) {
     96
     97
     98        Person director =getDirector(directorId);
     99        Movie movie = this.findById(movieId);
     100
     101        movie.setTitle(title);
     102        movie.setDescription(description);
     103        movie.setImageUrl(imageUrl);
     104        movie.setAiringDate(airingDate);
     105        movie.setImdbRating(rating);
     106        movie.setDirector(director);
     107
     108        this.movieActorsRepository.deleteAllByMovie(movie);
     109        this.movieGenresRepository.deleteAllByMovie(movie);
     110
     111        movie = this.movieRepository.save(movie);
     112        this.addActorsAndGenresForMovie(movie,actorIds,genreIds);
     113
     114        return movie;
     115    }
     116
     117    @Override
     118    public List<Person> findAllActorsForMovie(Movie movie) {
     119        return this.movieActorsRepository.findAllByMovie(movie)
     120                .stream()
     121                .map(MovieActors::getPerson)
     122                .collect(Collectors.toList());
     123    }
     124
     125    @Override
     126    public List<Genre> findAllGenresForMovie(Movie movie) {
     127        return this.movieGenresRepository.findAllByMovie(movie)
     128                .stream()
     129                .map(MovieGenres::getGenre)
     130                .collect(Collectors.toList());
     131    }
     132
     133    @Override
     134    public void likeMovie(Integer movieId, Integer userId) {
     135        User user = this.userRepository.findById(userId).orElseThrow(() -> new UserNotExistException(userId.toString()));
     136        Movie movie = this.findById(movieId);
     137
     138        this.movieLikesRepository.save(new MovieLikes(movie, user));
     139    }
     140
     141    @Override
     142    public void unlikeMovie(Integer movieId, Integer userId) {
     143        MovieLikesPK movieLikesPK = new MovieLikesPK(movieId,userId);
     144        this.movieLikesRepository.deleteById(movieLikesPK);
     145    }
     146
     147    @Override
     148    public List<Movie> findLikedMoviesByUser(User user) {
     149        return
     150                this.movieLikesRepository
     151                        .findAllByUser(user)
     152                        .stream()
     153                        .map(MovieLikes::getMovie)
     154                        .collect(Collectors.toList());
     155    }
     156
    33157
    34158    @Override
    35159    public void deleteById(Integer id) {
    36         movieRepository.deleteById(id);
     160        this.movieRepository.deleteById(id);
     161    }
     162
     163    @Override
     164    public void addGradeMovie(Integer movieId, User user, Grade grade) {
     165        MovieRatesPK key =  new MovieRatesPK(movieId, user.getUserId());
     166        Optional<MovieRates> movieRates = this.movieRatesRepository.findById(key);
     167        if (movieRates.isPresent()){
     168           MovieRates rates = movieRates.get();
     169            rates.setReason(grade.getReason());
     170            rates.setStarsRated(grade.getRating());
     171            this.movieRatesRepository.save(rates);
     172        }
     173        else{
     174            Movie movie = this.findById(movieId);
     175            MovieRates rates = new MovieRates(user,movie,grade.getReason(),grade.getRating());
     176            this.movieRatesRepository.save(rates);
     177        }
    37178    }
    38179
    39180    @Override
    40181    public List<Movie> searchByTitle(String title) {
    41         return movieRepository.findAllByTitleLike("%"+title+"%");
     182        return this.movieRepository.findAllByTitleLike("%"+title+"%");
     183    }
     184
     185    @Transactional
     186    void addActorsAndGenresForMovie(Movie movie, List<Integer> actorIds, List<Integer> genreIds)
     187    {
     188
     189        actorIds.stream()
     190                .map(this::findPersonById)
     191                .forEach(actor -> this.movieActorsRepository.save(new MovieActors(movie,actor)));
     192
     193        genreIds.stream()
     194                .map(this::findGenreById)
     195                .forEach(genre -> this.movieGenresRepository.save(new MovieGenres(movie,genre)));
     196
     197    }
     198    private Person getDirector(Integer directorId){
     199
     200        if (directorId != null)
     201            return this.findPersonById(directorId);
     202        return null;
     203
     204    }
     205    private Person findPersonById(Integer id){
     206        return this.personRepository.findById(id).orElseThrow(() -> new PersonNotExistException(id));
     207    }
     208    private Genre findGenreById(Integer id){
     209        return this.genreRepository.findById(id).orElseThrow(() -> new GenreNotExistException(id));
    42210    }
    43211}
  • src/main/java/com/wediscussmovies/project/service/impl/PersonServiceImpl.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.service.impl;
    22
    3 import com.wediscussmovies.project.model.*;
    4 import com.wediscussmovies.project.model.enumerations.PersonType;
     3import com.wediscussmovies.project.ajaxmodels.Grade;
     4import com.wediscussmovies.project.model.Movie;
     5import com.wediscussmovies.project.model.User;
     6import com.wediscussmovies.project.model.exception.MovieHasAlreadyDirector;
     7import com.wediscussmovies.project.model.exception.MovieIdNotFoundException;
     8import com.wediscussmovies.project.model.exception.PersonNotExistException;
     9import com.wediscussmovies.project.model.primarykeys.PersonRatesPK;
     10import com.wediscussmovies.project.model.relation.MovieActors;
     11import com.wediscussmovies.project.model.relation.MovieRates;
     12import com.wediscussmovies.project.model.relation.PersonRates;
     13import com.wediscussmovies.project.repository.MovieActorsRepository;
     14import com.wediscussmovies.project.repository.MovieRepository;
     15import com.wediscussmovies.project.repository.PersonRatesRepository;
    516import com.wediscussmovies.project.repository.PersonRepository;
     17import com.wediscussmovies.project.model.Person;
    618import com.wediscussmovies.project.service.PersonService;
    719import org.springframework.stereotype.Service;
    820
     21import javax.transaction.Transactional;
     22import java.sql.Date;
    923import java.util.List;
    1024import java.util.Optional;
     25import java.util.stream.Collectors;
    1126
    1227@Service
    1328public class PersonServiceImpl implements PersonService {
     29
    1430    private final PersonRepository personRepository;
     31    private final MovieRepository movieRepository;
     32    private final MovieActorsRepository movieActorsRepository;
     33    private final PersonRatesRepository personRatesRepository;
    1534
    1635
    17     public PersonServiceImpl(PersonRepository personRepository) {
     36    public PersonServiceImpl(PersonRepository personRepository,
     37                             MovieRepository movieRepository, MovieActorsRepository movieActorsRepository,
     38                             PersonRatesRepository personRatesRepository) {
    1839        this.personRepository = personRepository;
     40        this.movieRepository = movieRepository;
     41        this.movieActorsRepository = movieActorsRepository;
     42        this.personRatesRepository = personRatesRepository;
     43    }
     44
     45    @Override
     46    public List<Person> findAll() {
     47        return this.personRepository.findAll();
    1948    }
    2049
    2150    @Override
    2251    public List<Person> findAllDirectors() {
    23         return personRepository.findAllByType('D');
     52        return this.personRepository.findAllByType('D');
    2453    }
    2554
    2655    @Override
    27     public Optional<Person> findActorById(Integer id) {
    28         return personRepository.findPersonByPersonIdAndType(id, 'A');
     56    public Person findById(Integer id) {
     57        return this.personRepository.findById(id).orElseThrow(() -> new PersonNotExistException(id));
     58    }
     59
     60
     61
     62    @Override
     63    public List<Person> findAllActors() {
     64        return this.personRepository.findAllByType('A');
    2965    }
    3066
    3167    @Override
    32     public Optional<Person> findById(Integer person_id) {
    33         return personRepository.findById(person_id);
     68    @Transactional
     69    public Person save(String name, String surname, Character type, Date birthDate, String image_url,
     70                       String description,List<Integer> movieIds) {
     71
     72        Person person = this.personRepository.saveAndFlush(new Person(name,surname,type,birthDate,image_url,description));
     73
     74        if (movieIds!= null) {
     75            if (type.equals('A'))
     76                this.addActorForMovies(person, movieIds);
     77            else
     78                this.addDirectorForMovies(person, movieIds);
     79        }
     80         return person;
     81
    3482    }
    3583
    3684    @Override
    37     public Optional<Person> findDirectorById(Integer id) {
    38         return personRepository.findPersonByPersonIdAndType(id, 'D');
     85    @Transactional
     86    public Person edit(Integer personId, String name, String surname,
     87                       Character type, Date birthDate, String image_url, String description, List<Integer> movieIds) {
     88        Person person = this.findById(personId);
     89
     90        person.setName(name);
     91        person.setSurname(surname);
     92        person.setDateOfBirth(birthDate);
     93        person.setImageUrl(image_url);
     94        person.setType(type);
     95        person.setDescription(description);
     96
     97
     98        person = this.personRepository.saveAndFlush(person);
     99
     100            this.movieActorsRepository.deleteAllByPerson(person);
     101            this.removeMovieDirectorsBeforeEdit(person);
     102        if (movieIds != null) {
     103            if (type.equals('A'))
     104                this.addActorForMovies(person, movieIds);
     105            else
     106                this.addDirectorForMovies(person, movieIds);
     107        }
     108
     109        return person;
     110
    39111    }
    40112
    41113    @Override
    42     public List<Person> findAllActors() {
    43         return personRepository.findAllByType('A');
     114    public List<Person> findPersonsByNameOrSurname(Character type,String searchQuery) {
     115        if (searchQuery != null && searchQuery.isEmpty())
     116            return this.personRepository.findAllByTypeAndNameLikeOrSurnameLike(type,searchQuery,searchQuery);
     117        if (type.equals('D'))
     118            return this.findAllDirectors();
     119        return this.findAllActors();
     120
    44121    }
    45122
    46123    @Override
    47     public boolean save(Person person) {
    48         Person p = personRepository.save(person);
    49         if(p != null)
    50             return true;
    51         return false;
     124    public List<Movie> findAllMoviesByPerson(Person person) {
     125        if (person.getType().equals('A'))
     126            return this.movieActorsRepository
     127                .findAllByPerson(person)
     128                .stream()
     129                .map(MovieActors::getMovie)
     130                .collect(Collectors.toList());
     131        return this.movieRepository.findAllByDirector(person);
    52132    }
    53133
    54134    @Override
    55     public List<Person> findActorsByNameLike(String name) {
    56         return personRepository.findAllByTypeAndNameLike('A', name);
     135    public void deleteById(Integer id) {
     136        this.personRepository.deleteById(id);
    57137    }
    58138
    59139    @Override
    60     public List<Person> findActorsBySurnameLike(String surname) {
    61         return personRepository.findAllByTypeAndSurnameLike('A', surname);
     140    public void addGradePerson(Integer personId, User user, Grade grade) {
     141        PersonRatesPK key =  new PersonRatesPK(personId, user.getUserId());
     142        Optional<PersonRates> personRates = this.personRatesRepository.findById(key);
     143        if (personRates.isPresent()){
     144            PersonRates rates = personRates.get();
     145            rates.setReason(grade.getReason());
     146            rates.setStarsRated(grade.getRating());
     147            this.personRatesRepository.save(rates);
     148        }
     149        else{
     150            Person person = this.findById(personId);
     151            PersonRates rates = new PersonRates(user,person,grade.getReason(),grade.getRating());
     152            this.personRatesRepository.save(rates);
     153        }
     154
    62155    }
    63156
    64     @Override
    65     public List<Person> findDirectorsByNameLike(String name) {
    66         return personRepository.findAllByTypeAndNameLike('D', name);
     157
     158    private void addActorForMovies(Person person, List<Integer> movieIds){
     159
     160        movieIds.stream()
     161                .map(this::findMovieById)
     162                .forEach(m -> this.movieActorsRepository.save(new MovieActors(m,person)));
     163
     164    }
     165    private void addDirectorForMovies(Person person, List<Integer> movieIds){
     166        movieIds.stream()
     167                .map(this::findMovieById)
     168                .forEach(m -> this.addMovieDirector(m,person));
     169    }
     170    private void addMovieDirector(Movie movie,Person person){
     171        Person director = movie.getDirector();
     172        if (director != null)
     173            throw new MovieHasAlreadyDirector(movie.getTitle(),director.getName(),director.getSurname());
     174        movie.setDirector(person);
     175        this.movieRepository.save(movie);
     176    }
     177    private void removeMovieDirectorsBeforeEdit(Person person){
     178        this.movieRepository.findAllByDirector(person)
     179                .forEach(m ->{ m.setDirector(null); this.movieRepository.save(m); });
     180
    67181    }
    68182
    69     @Override
    70     public List<Person> findDirectorsBySurnameLike(String surname) {
    71         return personRepository.findAllByTypeAndSurnameLike('D', surname);
     183    private Movie findMovieById(Integer id){
     184        return this.movieRepository.findById(id).orElseThrow(() -> new MovieIdNotFoundException(id));
    72185    }
     186
    73187}
  • src/main/java/com/wediscussmovies/project/service/impl/ReplyServiceImpl.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.service.impl;
    22
    3 import com.wediscussmovies.project.model.*;
     3import com.wediscussmovies.project.model.Discussion;
     4import com.wediscussmovies.project.model.exception.DiscussionNotExistException;
     5import com.wediscussmovies.project.model.exception.ReplyNotExistException;
     6import com.wediscussmovies.project.model.primarykeys.ReplyPK;
     7import com.wediscussmovies.project.repository.DiscussionRepository;
    48import com.wediscussmovies.project.repository.ReplyRepository;
     9import com.wediscussmovies.project.model.Reply;
     10import com.wediscussmovies.project.model.User;
     11import com.wediscussmovies.project.repository.UserRepository;
    512import com.wediscussmovies.project.service.ReplyService;
    613import org.springframework.stereotype.Service;
    714
    8 import java.util.Optional;
     15import java.sql.Date;
     16import java.time.LocalDate;
     17import java.util.List;
    918
    1019@Service
    1120public class ReplyServiceImpl implements ReplyService {
     21
    1222    private final ReplyRepository replyRepository;
     23    private final DiscussionRepository discussionRepository;
    1324
    14     public ReplyServiceImpl(ReplyRepository replyRepository) {
     25    public ReplyServiceImpl(ReplyRepository replyRepository,
     26                            DiscussionRepository discussionRepository) {
    1527        this.replyRepository = replyRepository;
     28        this.discussionRepository = discussionRepository;
     29    }
     30
     31
     32
     33    @Override
     34    public void save(Integer discussionId, String text,User user) {
     35
     36        Discussion discussion = this.discussionRepository.findById(discussionId).orElseThrow(() -> new DiscussionNotExistException(discussionId));
     37
     38        Date date = Date.valueOf(LocalDate.now());
     39        this.replyRepository.insertInto(text,date,user.getUserId(),discussionId);
     40
    1641    }
    1742
    1843    @Override
    19     public Optional<Reply> findById(Long id) {
    20         return replyRepository.findById(1);
     44    public void likeReply(Integer replyId, Integer userId) {
     45        //da se implementira, promena vo baza
    2146    }
    2247
    2348    @Override
    24     public void delete(Reply r) {
    25         replyRepository.delete(r);
     49    public void unlikeReply(Integer replyId, Integer userId) {
     50        // da se implementira, promena vo baza
    2651    }
    2752
    2853    @Override
    29     public Reply save(Reply r) {
    30         return replyRepository.save(r);
     54    public List<Reply> findAllByDiscussion(Discussion discussion) {
     55        return this.replyRepository.findAllByDiscussion(discussion);
     56    }
     57
     58
     59    @Override
     60    public Reply edit(Integer replyId,Integer discussionId,String text) {
     61        ReplyPK replyPK = new ReplyPK(discussionId,replyId);
     62        Reply reply = this.replyRepository.findById(replyPK).orElseThrow();
     63        reply.setText(text);
     64        return  this.replyRepository.save(reply);
     65    }
     66
     67    @Override
     68    public void delete(Integer discussionId, Integer replyId) {
     69        this.replyRepository.deleteById(new ReplyPK(discussionId,replyId));
     70    }
     71
     72    @Override
     73    public Reply findById(Integer discussionId, Integer replyId) {
     74        ReplyPK replyPK  = new ReplyPK(discussionId,replyId);
     75        return this.replyRepository.findById(replyPK).orElseThrow(() -> new ReplyNotExistException(replyPK));
     76
    3177    }
    3278}
  • src/main/java/com/wediscussmovies/project/service/impl/UserServiceImpl.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.service.impl;
    22
    3 import com.wediscussmovies.project.model.*;
    4 import com.wediscussmovies.project.model.exception.PasswordsDontMatchException;
    5 import com.wediscussmovies.project.model.exception.UserWithEmailAlreadyExists;
    6 import com.wediscussmovies.project.model.exception.UserWithUsernameAlreadyExists;
     3import com.wediscussmovies.project.model.exception.InvalidArgumentsException;
     4import com.wediscussmovies.project.model.exception.PasswordsDoNotMatchException;
     5import com.wediscussmovies.project.model.exception.UserNotExistException;
     6import com.wediscussmovies.project.model.User;
     7import com.wediscussmovies.project.model.exception.UsernameAlreadyExistsException;
    78import com.wediscussmovies.project.repository.UserRepository;
    89import com.wediscussmovies.project.service.UserService;
     10import org.springframework.security.core.userdetails.UserDetails;
     11import org.springframework.security.core.userdetails.UsernameNotFoundException;
     12import org.springframework.security.crypto.password.PasswordEncoder;
    913import org.springframework.stereotype.Service;
    10 
    11 import javax.servlet.http.HttpServletRequest;
    12 import java.util.Optional;
    1314
    1415@Service
    1516public class UserServiceImpl implements UserService {
     17
    1618    private final UserRepository userRepository;
     19    private final PasswordEncoder passwordEncoder;
    1720
    18     public UserServiceImpl(UserRepository userRepository) {
     21
     22    public UserServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder) {
    1923        this.userRepository = userRepository;
     24        this.passwordEncoder = passwordEncoder;
    2025    }
    2126
    2227    @Override
    23     public Optional<User> login(String email, String password) {
    24         Optional<User> userEmail = userRepository.findByEmailAndPassword(email, password);
    25         Optional<User> userUsername = userRepository.findByUsernameAndPassword(email, password);
    26         if(userEmail.isPresent())
    27             return userEmail;
    28         else if(userUsername.isPresent())
    29             return userUsername;
    30         else
    31             return Optional.empty();
     28    public User findByUsername(String username) {
     29        return this.userRepository.findByUsername(username).orElseThrow(() -> new UserNotExistException(username));
     30    }
     31
     32
     33
     34    @Override
     35    public User register( String email, String username, String password, String confirmPassword
     36                                  , String name, String surname) {
     37
     38        if ( username.isEmpty() || password.isEmpty())
     39            throw new InvalidArgumentsException();
     40        if (!password.equals(confirmPassword))
     41            throw new PasswordsDoNotMatchException();
     42        if(this.userRepository.findByUsername(username).isPresent())
     43            throw new UsernameAlreadyExistsException(username);
     44        User user = new User(email,username,passwordEncoder.encode(password),name,surname);
     45        return userRepository.save(user);
     46
    3247    }
    3348
    3449    @Override
    35     public Optional<User> register(HttpServletRequest request, String email, String password, String confirmPassword,
    36                                    String username, String name, String surname) {
    37         if(email == null || email.isEmpty() || password == null || password.isEmpty() ||
    38                 confirmPassword == null || confirmPassword.isEmpty() || username == null || username.isEmpty() ||
    39                 name == null || name.isEmpty() || surname == null || surname.isEmpty()) {
    40             request.getSession().setAttribute("error", "Not all of the fields had a value in them, check again.");
    41             return Optional.empty();
    42         }
    43         if(userRepository.findByUsername(username).isPresent()){
    44             request.getSession().setAttribute("error", new UserWithUsernameAlreadyExists(username).getMessage());
    45             return Optional.empty();
    46         }
    47         if(userRepository.findByEmail(email).isPresent()){
    48             request.getSession().setAttribute("error", new UserWithEmailAlreadyExists(email).getMessage());
    49             return Optional.empty();
    50         }
    51         if(!password.equals(confirmPassword)){
    52             request.getSession().setAttribute("error", new PasswordsDontMatchException().getMessage());
    53             return Optional.empty();
    54         }
    55         User user = new User(email, username, password, name, surname);
    56         return Optional.of(userRepository.save(user));
     50    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
     51        return this.findByUsername(username);
    5752    }
    5853}
  • src/main/java/com/wediscussmovies/project/web/controller/MovieController.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.web.controller;
    22
    3 import com.wediscussmovies.project.exception.MovieIdNotFoundException;
    4 import com.wediscussmovies.project.model.*;
    5 
     3import com.wediscussmovies.project.model.Movie;
     4import com.wediscussmovies.project.model.Person;
     5import com.wediscussmovies.project.model.User;
    66import com.wediscussmovies.project.service.GenreService;
    77import com.wediscussmovies.project.service.MovieService;
    88import com.wediscussmovies.project.service.PersonService;
     9import lombok.Data;
     10import org.springframework.format.annotation.DateTimeFormat;
     11import org.springframework.security.authentication.AnonymousAuthenticationToken;
     12import org.springframework.security.core.Authentication;
     13import org.springframework.security.core.context.SecurityContextHolder;
     14import org.springframework.security.core.userdetails.UserDetails;
    915import org.springframework.stereotype.Controller;
    1016import org.springframework.ui.Model;
     
    1218
    1319import java.sql.Date;
    14 import java.util.LinkedList;
     20import java.time.LocalDate;
    1521import java.util.List;
    16 import java.util.Optional;
    1722
    1823@Controller
     
    3035
    3136    @GetMapping
    32     public String getMovies(@RequestParam(required = false) String titleQuery, Model model){
     37    public String getMovies(@RequestParam(required = false) String titleQuery, Model model,
     38                            @RequestParam(required = false) String error){
    3339        List<Movie> movies;
    3440        if(titleQuery == null ) {
     
    3945        }
    4046
     47        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
     48
     49        if (!(auth instanceof AnonymousAuthenticationToken)){
     50            UserDetails userDetails = (UserDetails) auth.getPrincipal();
     51            User user = (User) userDetails;
     52          model.addAttribute("likedMovies",this.movieService.findLikedMoviesByUser(user));
     53          model.addAttribute("user",user);
     54        }
    4155
    4256        model.addAttribute("movies", movies);
    4357        model.addAttribute("contentTemplate", "moviesList");
    44         return "list";
     58        if (error != null && !error.equals(" "))
     59            model.addAttribute("error",error);
     60        return "template";
    4561    }
    4662
     
    4864    @GetMapping("/add")
    4965    public String addMovie(Model model){
    50         model.addAttribute("directors", personService.findAllDirectors());
    51         model.addAttribute("actors", personService.findAllActors());
    52         model.addAttribute("genres", genreService.findAll());
     66
     67        addModelProperties(model);
    5368        model.addAttribute("contentTemplate", "moviesAdd");
    5469        return "template";
     
    5671
    5772
    58     @PostMapping("/{id}/delete")
    59     public String addMovie(@PathVariable Integer id){
    60         Optional<Movie> movie = movieService.findById(id);
    61         if(movie.isPresent()){
    62             movieService.deleteById(movie.get().getMovieId());
    63         }
    64         return "redirect:/movies";
     73    @GetMapping("/{id}/delete")
     74    public String deleteMovie(@PathVariable Integer id){
     75
     76       try {
     77           this.movieService.deleteById(id);
     78           return "redirect:/movies";
     79
     80       }
     81       catch (RuntimeException exc){
     82           return "redirect:/movies?error="+exc.getMessage();
     83       }
    6584    }
    6685
    67     @PostMapping("/add/confirm")
    68     public String addMoviePost(@RequestParam String title,
     86    @PostMapping("/save")
     87    public String saveMovie(
     88
     89
     90
     91            @RequestParam String title,
    6992                               @RequestParam String description,
    70                                @RequestParam String image_url,
    71                                @RequestParam Date airing_date,
    72                                @RequestParam Double rating,
    73                                @RequestParam Integer director_id,
     93                               @RequestParam String imageUrl,
     94                               @RequestParam(required = false) Double rating,
     95                               @RequestParam(required = false) Integer directorId,
     96                               @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate airingDate,
    7497                               @RequestParam List<Integer> actors,
    75                                @RequestParam List<Integer> genres,
    76                                Model model){
    77         if(title == null || title.isEmpty() ||
    78         description == null || description.isEmpty() ||
    79         image_url == null || image_url.isEmpty() ||
    80         airing_date == null ||
    81         rating == null ||
    82         director_id == null ||
    83         actors == null || actors.size() == 0 ||
    84         genres == null || genres.size() == 0)
    85         {
    86             model.addAttribute("error", "Not enough attributes, make sure all values are inputted, all of them are required");
    87             model.addAttribute("hasError", true);
    88             return "redirect:/add";
     98                               @RequestParam List<Integer> genres
     99                            ){
     100
     101        try {
     102            Movie movie = this.movieService.save(title,description,imageUrl,Date.valueOf(airingDate),rating,directorId,actors,genres);
     103
     104            return "redirect:/movies";
    89105        }
    90         List<Person> actorsList = new LinkedList<>();
    91         for(Integer id: actors){
    92             Optional<Person> person = personService.findActorById(id);
    93             if(person.isEmpty()){
    94                 model.addAttribute("error", "The actor with ID {" + id + "} was not found.");
    95                 model.addAttribute("hasError", true);
    96                 return "redirect:/add";
    97             }
    98             actorsList.add(person.get());
     106        catch (RuntimeException exc){
     107            return "redirect:/movies?error="+exc.getMessage();
    99108        }
     109    }
     110    @PostMapping("/save/{movieId}")
     111    public String updateMovie(
    100112
    101         List<Genre> genreList = new LinkedList<>();
    102         for(Integer id: genres){
    103             Optional<Genre> genre = genreService.findById(id);
    104             if(genre.isEmpty()){
    105                 model.addAttribute("error", "The genre with ID {" + id + "} was not found.");
    106                 model.addAttribute("hasError", true);
    107                 return "redirect:/add";
    108             }
    109             genreList.add(genre.get());
     113
     114            @PathVariable Integer movieId,
     115            @RequestParam String title,
     116            @RequestParam String description,
     117            @RequestParam String imageUrl,
     118            @RequestParam(required = false) Double rating,
     119            @RequestParam(required = false) Integer directorId,
     120            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate airingDate,
     121            @RequestParam List<Integer> actors,
     122            @RequestParam List<Integer> genres
     123    ){
     124
     125        try {
     126            Movie movie = this.movieService.edit(movieId,title,description,imageUrl,Date.valueOf(airingDate),rating,directorId,actors,genres);
     127
     128            return "redirect:/movies";
    110129        }
    111 
    112         Optional<Person> directorOp = personService.findDirectorById(director_id);
    113         if(directorOp.isEmpty()){
    114             model.addAttribute("error", "The director with ID {" + director_id + "} was not found.");
    115             model.addAttribute("hasError", true);
    116             return "redirect:/add";
     130        catch (RuntimeException exc){
     131            return "redirect:/movies?error="+exc.getMessage();
    117132        }
    118 
    119         Person director = directorOp.get();
    120 
    121         Movie movie = new Movie(title, description, image_url, airing_date,
    122                     rating, director.getPersonId());
    123 
    124         movieService.save(movie);
    125 
    126         return "redirect:/movies";
    127133    }
    128134
    129     @PostMapping("/edit/confirm")
    130     public String editMoviePost(
    131                                 @RequestParam Integer movie_id,
    132                                 @RequestParam String title,
    133                                @RequestParam String description,
    134                                @RequestParam String image_url,
    135                                @RequestParam Date airing_date,
    136                                @RequestParam Double rating,
    137                                @RequestParam Integer director_id,
    138                                @RequestParam List<Integer> actors,
    139                                @RequestParam List<Integer> genres,
    140                                Model model){
    141         if(
    142                 movie_id == null ||
    143                 title == null || title.isEmpty() ||
    144                 description == null || description.isEmpty() ||
    145                 image_url == null || image_url.isEmpty() ||
    146                 airing_date == null ||
    147                 rating == null ||
    148                 director_id == null ||
    149                 actors == null || actors.size() == 0 ||
    150                 genres == null || genres.size() == 0)
    151         {
    152             model.addAttribute("error", "Not enough attributes, make sure all values are inputted, all of them are required");
    153             model.addAttribute("hasError", true);
    154             return "redirect:/edit";
    155         }
    156135
    157         Optional<Movie> movieOptional = movieService.findById(movie_id);
    158         if(movieOptional.isEmpty()){
    159             model.addAttribute("error", "The movie with ID {" + movie_id + "} was not found.");
    160             model.addAttribute("hasError", true);
    161             return "redirect:/edit";
    162         }
    163         Movie movie = movieOptional.get();
    164 
    165         List<Person> actorsList = new LinkedList<>();
    166         for(Integer id: actors){
    167             Optional<Person> person = personService.findActorById(id);
    168             if(person.isEmpty()){
    169                 model.addAttribute("error", "The actor with ID {" + id + "} was not found.");
    170                 model.addAttribute("hasError", true);
    171                 return "redirect:/edit";
    172             }
    173             actorsList.add(person.get());
    174         }
    175 
    176         List<Genre> genreList = new LinkedList<>();
    177         for(Integer id: genres){
    178             Optional<Genre> genre = genreService.findById(id);
    179             if(genre.isEmpty()){
    180                 model.addAttribute("error", "The genre with ID {" + id + "} was not found.");
    181                 model.addAttribute("hasError", true);
    182                 return "redirect:/edit";
    183             }
    184             genreList.add(genre.get());
    185         }
    186 
    187         Optional<Person> directorOp = personService.findDirectorById(director_id);
    188         if(directorOp.isEmpty()){
    189             model.addAttribute("error", "The director with ID {" + director_id + "} was not found.");
    190             model.addAttribute("hasError", true);
    191             return "redirect:/edit";
    192         }
    193 
    194         Person director = directorOp.get();
    195 
    196         movieService.deleteById(movie_id);
    197 
    198 //      //  movie.setActors(actorsList);
    199 //        movie.setDirector(director);
    200 //        movie.setGenres(genreList);
    201 //        movie.setTitle(title);
    202 //        movie.setDescription(description);
    203 //        movie.setAringDate(airing_date);
    204 //        movie.setImageUrl(image_url);
    205 //        movie.setImbdRating(rating);
    206 
    207         movieService.save(movie);
    208 
    209         return "redirect:/movies";
    210     }
    211136
    212137    @GetMapping("/{id}/edit")
    213138    public String editMovie(@PathVariable Integer id, Model model){
    214         Movie movie = movieService.findById(id).orElseThrow(() -> new MovieIdNotFoundException(id));
    215         model.addAttribute("directors", personService.findAllDirectors());
     139        try {
     140            Movie movie = movieService.findById(id);
     141            addModelProperties(model);
     142            model.addAttribute("movie", movie);
     143            model.addAttribute("director",movie.getDirector());
     144            model.addAttribute("movieActors",movieService.findAllActorsForMovie(movie));
     145            model.addAttribute("movieGenres",movieService.findAllGenresForMovie(movie));
     146            model.addAttribute("contentTemplate", "moviesAdd");
     147            return "template";
     148
     149        }
     150        catch (RuntimeException exc){
     151            return "redirect:/movies?error="+exc.getMessage();
     152        }
     153
     154    }
     155    private void addModelProperties(Model model){
     156
     157        model.addAttribute("directors",  personService.findAllDirectors());
    216158        model.addAttribute("actors", personService.findAllActors());
    217159        model.addAttribute("genres", genreService.findAll());
    218         model.addAttribute("movie", movie);
    219         model.addAttribute("contentTemplate", "moviesEdit");
    220         return "template";
    221160    }
    222161}
  • src/main/java/com/wediscussmovies/project/web/controller/ReplyController.java

    r3ded84d re0ef1b1  
    11package com.wediscussmovies.project.web.controller;
    22
    3 import com.wediscussmovies.project.model.*;
     3import com.wediscussmovies.project.LoggedUser;
     4import com.wediscussmovies.project.model.Reply;
     5import com.wediscussmovies.project.model.User;
     6import com.wediscussmovies.project.model.primarykeys.ReplyPK;
    47import com.wediscussmovies.project.service.ReplyService;
     8import org.springframework.security.authentication.AnonymousAuthenticationToken;
     9import org.springframework.security.core.Authentication;
     10import org.springframework.security.core.context.SecurityContextHolder;
     11import org.springframework.security.core.userdetails.UserDetails;
    512import org.springframework.stereotype.Controller;
    613import org.springframework.ui.Model;
    7 import org.springframework.web.bind.annotation.GetMapping;
    8 import org.springframework.web.bind.annotation.PathVariable;
    9 import org.springframework.web.bind.annotation.PostMapping;
    10 import org.springframework.web.bind.annotation.RequestParam;
     14import org.springframework.web.bind.annotation.*;
    1115
    12 import java.util.Optional;
    1316
    1417@Controller
     18@RequestMapping("/replies")
    1519public class ReplyController {
    1620    private final ReplyService replyService;
     
    2024    }
    2125
    22     @GetMapping("/edit/{id}")
    23     public String getReplyEdit(@PathVariable Long id, Model model){
    24         Optional<Reply> reply = replyService.findById(id);
    25         if(reply.isEmpty())
    26             return "redirect:/movies";
    27         model.addAttribute("reply", reply.get());
    28         model.addAttribute("templateContext", "replyEdit");
     26    @GetMapping("/add/{discussionId}")
     27    public String addForm(@PathVariable Integer discussionId, Model model){
     28        model.addAttribute("discussionId",discussionId);
     29        model.addAttribute("contentTemplate","repliesAdd");
    2930        return "template";
    3031    }
    3132
    32     @PostMapping("/edit/confirm/{id}")
    33     public String getReplyEdit(@PathVariable Long id, @RequestParam String text){
    34         Optional<Reply> replyOp = replyService.findById(id);
    35         if(replyOp.isEmpty())
    36             return "redirect:/discussions";
    37         Reply reply = replyOp.get();
    38         replyService.delete(reply);
    39         reply.setText(text);
    40         replyService.save(reply);
    41         return "redirect:/discussions/"+reply.getDiscussionId();
     33    @GetMapping("/edit/{discussionId}/{replyId}")
     34    public String editForm(@PathVariable Integer discussionId,@PathVariable Integer replyId, Model model){
     35
     36        try {
     37            Reply reply = replyService.findById(discussionId,replyId);
     38            model.addAttribute("reply", reply);
     39            model.addAttribute("contentTemplate", "repliesAdd");
     40            return "template";
     41
     42
     43        }catch (RuntimeException exc){
     44            return "redirect:/discussions?error="+exc.getMessage();
     45
     46        }
    4247    }
     48    @PostMapping("/save")
     49    public String saveReply(
     50            @RequestParam Integer discussionId,
     51            @RequestParam String text){
     52
     53        try {
     54
     55            this.replyService.save(discussionId,text, LoggedUser.getLoggedUser());
     56            return "redirect:/discussions/"+discussionId;
     57
     58        }
     59        catch (RuntimeException exc){
     60            return "redirect:/discussions?error="+exc.getMessage();
     61
     62        }
     63    }
     64
     65    @PostMapping("/save/{replyId}")
     66    public String editReply(
     67                            @PathVariable Integer replyId,
     68                            @RequestParam Integer discussionId,
     69                            @RequestParam String text){
     70
     71        /*
     72            1. Da se realizira so ajax baranje na restController
     73         */
     74        try {
     75            Reply reply = replyService.edit(replyId,discussionId, text);
     76
     77            return "redirect:/discussions/" + reply.getDiscussion().getDiscussionId();
     78        }
     79        catch (RuntimeException exc){
     80            return "redirect:/discussions?error="+exc.getMessage();
     81        }
     82
     83    }
     84
    4385}
  • src/main/java/com/wediscussmovies/project/web/controller/UsersController.java

    r3ded84d re0ef1b1  
    1 //package com.wediscussmovies.project.web.controller;
    2 //
    3 //import com.wediscussmovies.project.model.PasswordEncoder;
    4 //import com.wediscussmovies.project.model.*;
    5 //import com.wediscussmovies.project.model.exception.InvalidUserCredentialsException;
    6 //import com.wediscussmovies.project.service.UserService;
    7 //import org.springframework.stereotype.Controller;
    8 //import org.springframework.ui.Model;
    9 //import org.springframework.web.bind.annotation.GetMapping;
    10 //import org.springframework.web.bind.annotation.PostMapping;
    11 //import org.springframework.web.bind.annotation.RequestParam;
    12 //
    13 //import javax.servlet.http.HttpServletRequest;
    14 //import java.security.NoSuchAlgorithmException;
    15 //import java.util.Optional;
    16 //
    17 //@Controller
    18 //public class UsersController{
    19 //    private final UserService userService;
    20 //
    21 //    public UsersController(UserService userService) {
    22 //        this.userService = userService;
    23 //    }
    24 //
    25 //    @GetMapping("/login")
    26 //    public String getLoginPage(Model model){
    27 //        return "login";
    28 //    }
    29 //
    30 //    @PostMapping("/login/confirm")
    31 //    public String confirmLogin(HttpServletRequest request, Model model,
    32 //                               @RequestParam String username,
    33 //                               @RequestParam String password){
    34 //        Optional<User> user;
    35 //        try{
    36 //            password = PasswordEncoder.getEncodedPasswordString(password);
    37 //        }
    38 //        catch (NoSuchAlgorithmException ex){
    39 //            model.addAttribute("hasError", true);
    40 //            model.addAttribute("error", ex.getMessage());
    41 //            return "login";
    42 //        }
    43 //
    44 //        try{
    45 //            user = this.userService.login(username, password);
    46 //            request.getSession().setAttribute("user", user);
    47 //            request.getSession().setAttribute("loggedIn",true);
    48 //            return "redirect:/movies";
    49 //        }
    50 //        catch (InvalidUserCredentialsException ex){
    51 //            model.addAttribute("hasError", true);
    52 //            model.addAttribute("error", ex.getMessage());
    53 //            return "login";
    54 //        }
    55 //    }
    56 //
    57 //    @GetMapping("/register")
    58 //    public String getRegisterPage(){
    59 //        return "register";
    60 //    }
    61 //
    62 //    @PostMapping("/login/confirm")
    63 //    public String confirmRegister(HttpServletRequest request,
    64 //                                  @RequestParam String username,
    65 //                                  @RequestParam String email,
    66 //                                  @RequestParam String password,
    67 //                                  @RequestParam String confirmPassword,
    68 //                                  @RequestParam String name,
    69 //                                  @RequestParam String surname){
    70 //        Optional<User> user;
    71 //
    72 //        try{
    73 //            password = PasswordEncoder.getEncodedPasswordString(password);
    74 //            confirmPassword = PasswordEncoder.getEncodedPasswordString(confirmPassword);
    75 //        }
    76 //        catch (NoSuchAlgorithmException ex){
    77 //            request.getSession().setAttribute("error", "Contact the administrators!");
    78 //            request.getSession().setAttribute("hasError", "true");
    79 //            return "redirect:/movies";
    80 //        }
    81 //
    82 //        user = this.userService.register(request, email, password, confirmPassword, username, name, surname);
    83 //        if(user.isEmpty()){
    84 //            request.setAttribute("hasError", "true");
    85 //        }else{
    86 //            request.getSession().setAttribute("hasError", "false");
    87 //            request.getSession().setAttribute("user", user.get());
    88 //            request.getSession().setAttribute("loggedIn",true);
    89 //        }
    90 //        return "redirect:/movies";
    91 //    }
    92 //
    93 //    @GetMapping
    94 //    public String logout(HttpServletRequest request){
    95 //        request.getSession().invalidate();
    96 //        return "redirect:/login";
    97 //    }
    98 //}
     1package com.wediscussmovies.project.web.controller;
     2
     3
     4import com.wediscussmovies.project.LoggedUser;
     5import com.wediscussmovies.project.model.exception.InvalidArgumentsException;
     6import com.wediscussmovies.project.model.exception.PasswordsDoNotMatchException;
     7import com.wediscussmovies.project.service.MovieService;
     8import com.wediscussmovies.project.service.UserService;
     9import org.springframework.stereotype.Controller;
     10import org.springframework.ui.Model;
     11import org.springframework.web.bind.annotation.GetMapping;
     12import org.springframework.web.bind.annotation.PostMapping;
     13import org.springframework.web.bind.annotation.RequestMapping;
     14import org.springframework.web.bind.annotation.RequestParam;
     15
     16@Controller
     17@RequestMapping
     18public class UsersController{
     19    private  final UserService userService;
     20    private final MovieService movieService;
     21
     22    public UsersController(UserService userService, MovieService movieService) {
     23        this.userService = userService;
     24        this.movieService = movieService;
     25    }
     26    @PostMapping("/register")
     27    public String register(@RequestParam String username,
     28                           @RequestParam String password,
     29                           @RequestParam String repeatedPassword,
     30                           @RequestParam String email,
     31                           @RequestParam String name,
     32                           @RequestParam String surname) {
     33        try{
     34            this.userService.register(email,username,password,repeatedPassword,name,surname);
     35            return "redirect:/login";
     36        } catch (InvalidArgumentsException | PasswordsDoNotMatchException exception) {
     37            return "redirect:/register?error=" + exception.getMessage();
     38        }
     39    }
     40    @GetMapping("/register")
     41    public String getRegisterPage(@RequestParam(required = false) String error, Model model) {
     42        addModelError(model,error);
     43        model.addAttribute("contentTemplate","register");
     44        return "template";
     45    }
     46    @GetMapping("/login")
     47    public String getLoginPage(@RequestParam(required = false) String error,Model model){
     48        addModelError(model,error);
     49        model.addAttribute("contentTemplate","login");
     50        return "template";
     51    }
     52
     53    private void addModelError(Model model,String error){
     54        if(error != null && !error.isEmpty()) {
     55            model.addAttribute("hasError", true);
     56            model.addAttribute("error", error);
     57        }
     58    }
     59    @GetMapping("/favoriteList")
     60    public String getFavoriteList(Model model){
     61        model.addAttribute("movies",this.movieService.findLikedMoviesByUser(LoggedUser.getLoggedUser()));
     62        model.addAttribute("contentTemplate","favoriteList");
     63        return "template";
     64
     65    }
     66
     67
     68}
Note: See TracChangeset for help on using the changeset viewer.