<repo_name>sai374/music-application<file_sep>/src/main/java/com/manipal/demo/model/Song.java
package com.manipal.demo.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import io.swagger.annotations.ApiModelProperty;

@Entity
@Table(name = "Song")
public class Song {
	
	@Id
	@ApiModelProperty(notes = "ID of the Song", name = "songId", value="S101")
    private String songId;
	@ApiModelProperty(notes = "Title of the Song", name = "songTitle", value="Breathless")
    private String songTitle;
	@ApiModelProperty(notes = "Singer of the Song", name = "singer", value="<NAME>")
    private String singer;
	@ApiModelProperty(notes = "Album of the Song", name = "albumName", value="Breathless")
    private String albumName;
	@ApiModelProperty(notes = "Url of the Song", name = "url", value="https://www.youtube.com/watch?v=HHkHxTeaK_I")
    private String url;

    public Song() {}
    
    public Song(String songId, String songTitle, String singer, String albumName, String url) {
        this.songId = songId;
        this.songTitle = songTitle;
        this.singer = singer;
        this.albumName = albumName;
        this.url = url;
    }

	public String getSongId() {
		return songId;
	}

	public void setSongId(String songId) {
		this.songId = songId;
	}

	public String getSongTitle() {
		return songTitle;
	}

	public void setSongTitle(String songTitle) {
		this.songTitle = songTitle;
	}

	public String getSinger() {
		return singer;
	}

	public void setSinger(String singer) {
		this.singer = singer;
	}

	public String getAlbumName() {
		return albumName;
	}

	public void setAlbumName(String albumName) {
		this.albumName = albumName;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}
   
}
<file_sep>/README.md
# music-app-management
<file_sep>/src/test/java/com/manipal/demo/controller/SongControllerTest.java
package com.manipal.demo.controller;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.manipal.demo.controller.SongController;
import com.manipal.demo.model.Song;
import com.manipal.demo.service.impl.SongServiceImpl;

@WebMvcTest(SongController.class)
public class SongControllerTest {
	
	@Autowired
	MockMvc mvc;
	
	@MockBean
	private SongServiceImpl songService;
	
	@Test
	void testFindAll() throws Exception {
		mvc.perform(MockMvcRequestBuilders
				.get("/songs")
				.accept(MediaType.APPLICATION_JSON))
				.andDo(print())
				.andExpect(status().isOk());
	}
	
	@Test
	void testFindSongByTitle() throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		Song song = new Song("S106","Ee petaku nene mestri","SP Balasubramanyam","Muta Mestri","https://www.youtube.com/watch?v=c16sIwFhVgQ");
		mvc.perform(MockMvcRequestBuilders
				.get("/songs/title/Ee petaku nene mestri")
				.content(objectMapper.writeValueAsString(song))
				.accept(MediaType.APPLICATION_JSON)
				.contentType(MediaType.APPLICATION_JSON))
				.andDo(print())
				.andExpect(status().isOk());
	}
}
<file_sep>/src/main/java/com/manipal/demo/service/impl/SongServiceImpl.java
package com.manipal.demo.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.manipal.demo.exception.SongNotFoundException;
import com.manipal.demo.model.Song;
import com.manipal.demo.repository.SongRepo;
import com.manipal.demo.service.SongService;

@Service
public class SongServiceImpl implements SongService {
	@Autowired
    private SongRepo songRepo;

	@Override
    public List<Song> findAllSongs() throws SongNotFoundException {
    	try {
			List<Song> songs = songRepo.findAll();
			if(songs.size() == 0) {
				throw new SongNotFoundException("Songs are not available now. Try after some time.");
			}
			return songs;
		} catch(SongNotFoundException snfe) {
			throw new SongNotFoundException("Songs are not available now. Try after some time.");
		}
    }

	@Override
	public Song findSongByTitle(String title) throws SongNotFoundException {
		try {
			Song song = songRepo.findBySongTitle(title);
			if(song==null) {
				throw new SongNotFoundException("Song with title "+title+" is not found.");
			}
			return song;
		} catch(SongNotFoundException snfe) {
			throw new SongNotFoundException("Song with title "+title+" is not found.");
		}
	}	 

	@Override
    public List<Song> findSongsBySinger(String singer) throws SongNotFoundException {
    	try {
			List<Song> songs = songRepo.findBySinger(singer);
			if(songs.size()==0) {
				throw new SongNotFoundException("Songs sung by "+singer+" are not available.");
			}
			return songs;
		} catch(SongNotFoundException snfe) {
			throw new SongNotFoundException("Songs sung by "+singer+" are not available.");
		}
    }

	@Override
    public List<Song> findSongsByAlbum(String album) throws SongNotFoundException {
    	try {
			List<Song> songs = songRepo.findByAlbumName(album);
			if(songs.size()==0) {
				throw new SongNotFoundException("Album "+album+" is not found.");
			}
			return songs;
		} catch(SongNotFoundException snfe) {
			throw new SongNotFoundException("Album "+album+" is not found.");
		}
    }

	@Override
    public Song addSongToMusicStore(Song song) throws SongNotFoundException {
		if(songRepo.searchSong(song.getSongId())!=null) {
			throw new SongNotFoundException("Song id already exists. Give new song id.");
		}
        return songRepo.save(song);
    }

	@Override
     public Song getSongById(String songId) throws SongNotFoundException {
            return songRepo.findById(songId).orElseThrow(() -> new SongNotFoundException("No songs found."));
    }

	@Override
	public Song updateDetails(Song song) throws SongNotFoundException {
		songRepo.findById(song.getSongId()).orElseThrow(() -> new SongNotFoundException("Updation cannot be done. Song with this song id is not found."));
		return songRepo.save(song);
	}

	@Override
    public  void removeSong(String songId) throws SongNotFoundException {
    	songRepo.findById(songId).orElseThrow(() -> new SongNotFoundException("Deletion cannot be done. Song with this song id is not found."));
            songRepo.deleteById(songId);
    }
}
<file_sep>/src/test/java/com/manipal/demo/controller/UserControllerTest.java
package com.manipal.demo.controller;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.manipal.demo.model.User;
import com.manipal.demo.service.impl.UserServiceImpl;
import com.manipal.demo.service.impl.UserWishlistServiceImpl;

@WebMvcTest(UserController.class)
public class UserControllerTest {
	
	@Autowired
	MockMvc mvc;
	
	@MockBean
	private UserServiceImpl userService;
	
	@MockBean
	private UserWishlistServiceImpl userWishlistService;
	
	/*@Test
	void checkDetailsTest() throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		User user = new User("U101", "Sai", "S<PASSWORD>");
		mvc.perform(MockMvcRequestBuilders
				.post("/users/validate")
				.content(objectMapper.writeValueAsString(user))
				.accept(MediaType.APPLICATION_JSON)
		        .contentType(MediaType.APPLICATION_JSON))
				.andExpect(status().isOk());
	}*/
	
	@Test
	void addDetailsTest() throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		User user = new User("U101", "Sai", "S<PASSWORD>");
		mvc.perform(post("/users")
				.content(objectMapper.writeValueAsString(user))
				.accept(MediaType.APPLICATION_JSON)
				.contentType(MediaType.APPLICATION_JSON))
				.andDo(print())
				.andExpect(status().isOk());
	}
	
	@Test
	void updateDetailsTest() throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		User user = new User("U101", "<NAME>", "<PASSWORD>");
		mvc.perform(MockMvcRequestBuilders
				.post("/users")
				.content(objectMapper.writeValueAsString(user))
				.accept(MediaType.APPLICATION_JSON)
				.contentType(MediaType.APPLICATION_JSON))
				.andDo(print())
				.andExpect(status().isOk());
	}
}
<file_sep>/src/main/java/com/manipal/demo/service/SongService.java
package com.manipal.demo.service;

import java.util.List;

import com.manipal.demo.exception.SongNotFoundException;
import com.manipal.demo.model.Song;

public interface SongService {
	
	public List<Song> findAllSongs() throws SongNotFoundException;
	public Song findSongByTitle(String title) throws SongNotFoundException;
	public List<Song> findSongsBySinger(String singer) throws SongNotFoundException;
	public List<Song> findSongsByAlbum(String album) throws SongNotFoundException;
	public Song addSongToMusicStore(Song song) throws SongNotFoundException;
	public Song getSongById(String songId) throws SongNotFoundException;
	public Song updateDetails(Song song) throws SongNotFoundException;
	public  void removeSong(String songId) throws SongNotFoundException;
}
<file_sep>/src/main/java/com/manipal/demo/repository/SongRepo.java
package com.manipal.demo.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.manipal.demo.model.Song;

@Repository
public interface SongRepo extends JpaRepository<Song, String> {
	
	public Song findBySongTitle(String title);
	public List<Song> findBySinger(String singer);
	public List<Song> findByAlbumName(String album);
	
	@Query(value = "SELECT * FROM Song s WHERE s.song_id = (:songId)", nativeQuery = true)
	public Song searchSong(String songId);
}
<file_sep>/src/main/java/com/manipal/demo/model/Admin.java
package com.manipal.demo.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import io.swagger.annotations.ApiModelProperty;

@Entity
@Table(name = "Admin")
public class Admin {
	@Id
	@ApiModelProperty(notes = "ID of the Admin", name = "adminId", value="A101")
    private String adminId;
	@ApiModelProperty(notes = "Password of the Admin", name = "adminPassword", value="<PASSWORD>")
    private String adminPassword;

    public Admin() {}
    
    public Admin(String adminId, String adminPassword) {
        this.adminId = adminId;
        this.adminPassword = <PASSWORD>;
    }

	public String getAdminId() {
		return adminId;
	}

	public void setAdminId(String adminId) {
		this.adminId = adminId;
	}

	public String getAdminPassword() {
		return <PASSWORD>Password;
	}

	public void setAdminPassword(String adminPassword) {
		this.adminPassword = <PASSWORD>;
	}
    
}
<file_sep>/src/main/java/com/manipal/demo/service/UserService.java
package com.manipal.demo.service;

import com.manipal.demo.exception.UserNotFoundException;
import com.manipal.demo.model.User;

public interface UserService {
	
	public User addDetails(User user) throws UserNotFoundException;
	public User checkDetails(String userId, String password);
	public User updateDetails(User user) throws UserNotFoundException;
	public void deleteAccount(String userId);
	public User getUserById(String userId) throws UserNotFoundException;
	public Boolean validateUserId(String userId);
}
<file_sep>/src/main/java/com/manipal/demo/controller/UserController.java
package com.manipal.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.manipal.demo.exception.UserNotFoundException;
import com.manipal.demo.model.User;
import com.manipal.demo.service.impl.UserServiceImpl;
import com.manipal.demo.service.impl.UserWishlistServiceImpl;

import io.swagger.annotations.ApiOperation;

@CrossOrigin(origins = "http://localhost:3000")
@ApiOperation(value = "/users", tags = "User Controller")
@RestController
@RequestMapping("/users")
public class UserController {
	
	@Autowired
    private UserServiceImpl userService;
	
	@Autowired
    private UserWishlistServiceImpl userWishlistService;

    public Boolean validateUserId( String userId) {
        return userService.validateUserId(userId);
    }


    @ApiOperation(value = "User Registration", response = User.class)
    @PostMapping()
    public User addDetails(@RequestBody User user) throws UserNotFoundException {
        return userService.addDetails(user);
    }

    @ApiOperation(value = "User Login")
    @GetMapping("/validate/{userId}/{userPassword}")
    public String checkDetails(@PathVariable String userId, @PathVariable String userPassword) throws UserNotFoundException {
    	if(userService.checkDetails(userId, userPassword) != null) {
    		return "Login Successful";
    	}
    	return "Wrong Credentials";
    }

    @ApiOperation(value = "Update User Details", response = User.class)
    @PutMapping("/{userId}")
    public User updateDetails(@PathVariable String userId, @RequestBody User userDetails) throws UserNotFoundException {
        User user = userService.getUserById(userId);
        user.setUserName(userDetails.getUserName());
        user.setUserPassword(<PASSWORD>());
        User updatedUser = userService.updateDetails(user);
        return updatedUser;
    }

    @ApiOperation(value = "Delete User Account", response = User.class)
    @DeleteMapping("/{userId}")
    public String deleteAccount(@PathVariable String userId) throws UserNotFoundException {
        User user = userService.getUserById(userId);
        userWishlistService.deleteAllSongsByUserId(userId);
        userService.deleteAccount(userId);
        return "Account Deleted Succesfully";
    }
}
<file_sep>/src/test/java/com/manipal/demo/controller/AdminControllerTest.java
package com.manipal.demo.controller;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.manipal.demo.model.Admin;
import com.manipal.demo.repository.AdminRepo;
import com.manipal.demo.service.impl.AdminServiceImpl;

@WebMvcTest(AdminController.class)
public class AdminControllerTest {
	
	@Autowired
	MockMvc mvc;
	
	@MockBean
	private AdminServiceImpl adminService;
	
	@MockBean
	private AdminRepo adminRepo;
	
	
	@Test
	void checkDetailsTest() throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		Admin admin = new Admin("A101", "<PASSWORD>");
		mvc.perform(MockMvcRequestBuilders
				.post("/admins/valid")
				.content(objectMapper.writeValueAsString(admin))
				.accept(MediaType.APPLICATION_JSON)
		        .contentType(MediaType.APPLICATION_JSON))
				.andExpect(status().isOk());
	}
	
	@Test
	void updateDetailsTest() throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		Admin admin = new Admin("A101", "<PASSWORD>");
		mvc.perform(MockMvcRequestBuilders
				.put("/admins/A101")
				.content(objectMapper.writeValueAsString(admin))
				.accept(MediaType.APPLICATION_JSON)
				.contentType(MediaType.APPLICATION_JSON))
				.andDo(print())
				.andExpect(status().isOk());
	}
}
<file_sep>/.metadata/version.ini
#Sat Dec 05 22:31:32 IST 2020
org.eclipse.core.runtime=2
org.eclipse.platform=4.17.0.v20200902-1800
<file_sep>/src/main/java/com/manipal/demo/repository/UserWishlistRepo.java
package com.manipal.demo.repository;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.manipal.demo.model.Song;
import com.manipal.demo.model.UserWishlist;

@Repository
public interface UserWishlistRepo extends JpaRepository<UserWishlist, String> {

	@Query("SELECT song FROM Song song  WHERE song.songId IN (SELECT u.songId FROM UserWishlist u WHERE u.userId = ?1)")
	public List<Song> findAllSongsFromsWishlist(String userId);
	//public List<Song> findAllSongsFromsWishlist(@Param("userId") String userId);

	@Query("SELECT song FROM Song song where song.songId IN (SELECT u.songId FROM UserWishlist u  WHERE u.songId = ?2 AND u.userId = ?1)")
	public Song findSongsByTitleFromWishlist(String userId, String songId);

	@Query(value = "SELECT song FROM Song song WHERE song.songId IN (SELECT u.songId FROM UserWishlist u WHERE u.songId = ?2 AND u.userId = ?1)")
	public Song findSongsByAlbumFromWishlist(String userId, String songId);

	@Transactional
	@Modifying
	@Query(value = "DELETE FROM User_Wishlist  WHERE user_id  = (:userId)", nativeQuery = true)
	public void deleteAllSongsByUserId(@Param("userId") String userId);

	@Query(value = "SELECT song_id FROM User_Wishlist  WHERE song_id = (:songId)", nativeQuery = true)
	public String findSongBySongIdFromWishlist(@Param("songId") String songId);

	@Transactional
	@Modifying
	@Query(value = "DELETE FROM User_Wishlist  WHERE user_id  = (:userId) AND song_id = (:songId)", nativeQuery = true)
	public void deleteSong(@Param("userId") String userId, @Param("songId") String songId);
}
