7 Commits
lab03 ... lab05

57 changed files with 2696 additions and 550 deletions

View File

@@ -17,7 +17,19 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-devtools'
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
implementation 'org.webjars:bootstrap:5.1.3'
implementation 'org.webjars:jquery:3.6.0'
implementation 'org.webjars:font-awesome:6.1.0'
implementation 'org.jetbrains:annotations:24.0.0'
implementation 'org.jetbrains:annotations:24.0.0'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.hibernate.validator:hibernate-validator'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {

View File

@@ -1,110 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>LabWork02</title>
<script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body class="bg-light">
<div class="container">
<div class="py-5 text-center"><h2>Лабораторная работа 2</h2></div>
<div class="row">
<div>
<form>
<div class="row">
<div class="col-md-6 mb-3">
<label for="input1">Значение 1 (string или double)</label>
<input class="form-control" id="input1" placeholder="Введите значение 1">
</div>
<div class="col-md-6 mb-3">
<label for="input1">Значение 2 (string или double)</label>
<input class="form-control" id="input2" placeholder="Введите значение 2">
</div>
</div>
<div class="row">
<div class="form-group">
<label for="operator">Выберите функцию</label>
<select class="form-control" id="operator">
<option value>Выбрать...</option>
<option value="Func1">(string, double)Сумма</option>
<option value="Func2">(double)Минимум, (string)Сумма в верхний регистр</option>
<option value="Func3">(double)Mаксимум, (string)Разделить</option>
<option value="Func4">(double)Число 1 в степени числа 2, (string)Сумма в нижний регистр</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="operator">Выберите тип данных</label>
<select class="form-control" id="Type">
<option value>Выбрать...</option>
<option value="str">String</option>
<option value="double">Double</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="result">Результат</label>
<input type="text" class="form-control result" id="result" readonly>
<hr class="mb-4">
<button type="button" class="btn btn-primary btn-block" onclick="calculate()">Посчитать</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!--<div class="container mt-4">-->
<!-- <div class="row justify-content-center">-->
<!-- <div class="col-lg-6">-->
<!-- <h3 class="text-center font-weight-light my-2">Лабораторная работа 2</h3>-->
<!-- <form>-->
<!-- <div class="form-row">-->
<!-- <div class="col">-->
<!-- <div class="form-group">-->
<!-- <label for="input1">Значение 1 (string или double)</label>-->
<!-- <input class="form-control" id="input1" placeholder="Введите значение 1">-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="col">-->
<!-- <div class="form-group">-->
<!-- <label for="input2">Значение 2 (string или double)</label>-->
<!-- <input class="form-control" id="input2" placeholder="Введите значение 2">-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="col">-->
<!-- <div class="form-group">-->
<!-- <label for="operator">Выбрать функцию...</label>-->
<!-- <select class="form-control" id="operator">-->
<!-- <option value="Func1">Сумма</option>-->
<!-- <option value="Func2">Минимум, Сумма в верхний регистр</option>-->
<!-- <option value="Func3">Mаксимум, Разделить</option>-->
<!-- <option value="Func4">Число 1 в степени числа 2, Сумма в нижний регистр</option>-->
<!-- </select>-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="col">-->
<!-- <div class="form-group">-->
<!-- <label for="operator">Выбрать тип данных...</label>-->
<!-- <select class="form-control" id="Type">-->
<!-- <option value="str">String</option>-->
<!-- <option value="double">Double</option>-->
<!-- </select>-->
<!-- </div>-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="form-group">-->
<!-- <label for="result">Результат</label>-->
<!-- <input type="text" class="form-control result" id="result" readonly>-->
<!-- </div>-->
<!-- <button type="button" class="btn btn-primary btn-block" onclick="calculate()">Посчитать</button>-->
<!-- </form>-->
<!-- </div>-->
<!-- </div>-->
<!--</div>-->
<script src = "script.js"></script>
</body>
</html>

View File

@@ -1,15 +0,0 @@
{
"name": "IP",
"version": "1.0.0",
"main": "index.html",
"scripts": {
"start": "http-server -p 3001 ./",
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"bootstrap": "5.2.1"
},
"devDependencies": {
"http-server": "^14.1.1"
}
}

View File

@@ -1,13 +0,0 @@
'use strict'
async function calculate(){
let num1 = document.getElementById("input1").value
let num2 = document.getElementById("input2").value
let operator = document.getElementById("operator").value
let result = document.getElementById("result")
let type = document.getElementById("Type").value
let response = await fetch(`http://localhost:8080/${operator}?Type=${type}&value1=${num1}&value2=${num2}`)
let res = await response.text()
result.value = res
}

View File

@@ -0,0 +1,48 @@
<template>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav justify-content-center">
<li class="nav-item">
<router-link to="/songs" class="nav-link">Песни</router-link>
</li>
<li class="nav-item">
<router-link to="/albums" class="nav-link">Альбомы</router-link>
</li>
<li class="nav-item">
<router-link to="/artists" class="nav-link">Исполнители</router-link>
</li>
</ul>
</div>
</div>
</nav>
</template>
<style>
.navbar-brand {
font-size: 2rem;
font-weight: bold;
}
.nav-link {
color: black;
font-weight: bold;
transition: color 0.3s ease-in-out;
}
.nav-link:hover {
color: white;
}
.nav-link {
color: grey;
}
</style>
<script>
export default {
}
</script>

View File

@@ -0,0 +1,7 @@
export default class Album{
constructor(data) {
this.id = data?.id;
this.albumName = data?.albumName;
this.artistIds = data?.artistIds;
}
}

View File

@@ -0,0 +1,7 @@
export default class Artist{
constructor(data) {
this.id = data?.id;
this.artistName = data?.artistName;
this.albumIds = data?.albumIds;
}
}

8
front/src/models/Song.js Normal file
View File

@@ -0,0 +1,8 @@
export default class Song{
constructor(data) {
this.id = data?.id;
this.songName = data?.songName;
this.duration = data?.duration;
this.album = data?.album;
}
}

408
front/src/pages/albums.vue Normal file
View File

@@ -0,0 +1,408 @@
<template>
<div class="container mt-4">
<h1 class="text-center mb-4">Альбомы</h1>
<button class="btn btn-primary mr-2" @click="openModal('create')">Добавить</button>
<table class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>Название</th>
<th>Альбомы</th>
<th>Исполнители</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="alb in albums" :key="alb.id">
<td>{{ alb.albumName }}</td>
<td>
<div class="d-flex flex-column">
<button class="btn btn-primary mb-2" @click="OpenModelForSongs(); getSongsFromAlbum(alb.id)">Просмотр песен</button>
<button class="btn btn-primary mb-2" @click="OpenModelForAddSongs(alb); getSongsFromUndefinedAlbum()">Добавить песен в альбом</button>
</div>
</td>
<td>
<div class="d-flex flex-column">
<button class="btn btn-primary mb-2" @click="OpenModelForArtists(); getArtistsInAlbum(alb.id)">Просмотр исполнителей</button>
<button class="btn btn-primary mb-2" @click="OpenModelForAddArtists('edit', alb);">Добавить исполнителей в альбом</button>
</div>
</td>
<td>
<div class="d-flex flex-column">
<button class="btn btn-primary mb-2" @click="openModal('edit', alb)">Изменить</button>
<button class="btn btn-danger mb-2" @click="deleteAlbum(alb.id)">Удалить</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!--Форма для привязки артиста и альбомов -->
<div class="modal" tabindex="-1" id="openModalForAddArtists">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Добавить исполнителей</h5>
</div>
<div class="modal-body">
<form>
<div class="form-album">
<label for="albumName">Имя:</label>
<input readonly type="text" class="form-control" id="albumName" name="albumName" v-model="album.albumName">
</div>
<div class="form-album">
<label for="name">Выберите исполнителей:</label>
<ul class="list-album">
<li class="list-album-item" v-for="artist in artists" :key="artist.id">
<div class="form-check">
<input class="form-check-input" type="checkbox" v-model="selectedArtists" :value="artist.id" v-bind:checked="open.includes(artist.id)" id="albumCheck{{ artist.id }}">
<label class="form-check-label" for="albumCheck{{ artist.id }}">{{ artist.artistName }}</label>
</div>
</li>
</ul>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModalForAddArtists()">Закрыть</button>
<button type="button" class="btn btn-primary" @click="addArtistToAlbum(album.id, selectedArtists)">Добавить</button>
</div>
</div>
</div>
</div>
<!-- Модальное окно песен в альбом-->
<div class="modal" tabindex="-1" id="ModalForAddSongs">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Добавить песни</h5>
</div>
<div class="modal-body">
<form>
<div class="form-album">
<label for="albumName">Название:</label>
<input type="text" class="form-control" id="albumName" name="albumName" v-model="album.albumName">
</div>
<div class="form-album">
<label for="name">Выберите песни:</label>
<ul class="list-album">
<li class="list-album-item" v-for="song in songs" :key="song.id">
<div class="form-check">
<input class="form-check-input" type="checkbox" :id="'songCheck' + song.id" :value="song.id" v-model="selectedSongs">
<label class="form-check-label" :for="'songCheck' + song.id">{{ song.songName }}</label>
</div>
</li>
</ul>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="CloseModalForAddSongs()">Закрыть</button>
<button type="button" class="btn btn-primary" @click="saveSongs(album.id)">Сохранить</button>
</div>
</div>
</div>
</div>
<!-- Модальное окно и изменения-->
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Альбом</h5>
</div>
<div class="modal-body">
<form>
<div class="form-album">
<label for="albumName">Название:</label>
<input type="text" class="form-control" id="albumName" name="albumName" v-model="album.albumName">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-primary" v-if="album.status === 'create'" @click="addAlbum(album)">Создать</button>
<button type="button" class="btn btn-primary" v-else @click="editAlbum(album)">Сохранить</button>
</div>
</div>
</div>
</div>
<!-- Модальное окно для просмотра песен в альбоме-->
<div class="modal" tabindex="-1" id="ModelForSongs">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Песни</h5>
</div>
<div class="modal-body">
<form>
<div class="form-album">
<table class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>Название</th>
<th>Продолжительность</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="son in songs" :key="son.id">
<td>{{ son.songName }}</td>
<td>{{ son.duration }}</td>
<td>
<td>
<button class="btn btn-danger mr-2" @click="deleteSongFromAlbum(son.id)">Удалить</button>
</td>
</td>
</tr>
</tbody>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="ModelForSongs" @click="closeModelForSongs()">Закрыть</button>
</div>
</div>
</div>
</div>
<!-- Модальное окно для просмотра исполнителей в альбомове-->
<div class="modal" tabindex="-1" id="ModelForArtists">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Исполнители</h5>
</div>
<div class="modal-body">
<form>
<div class="form-album">
<table class="thead-inverse table table-striped">
<thead>
<tr>
<th>Имя</th>
</tr>
</thead>
<tbody>
<tr v-for="art in artistsInAlbum" :key="art.id">
<td>{{ art.artistName }}</td>
</tr>
</tbody>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="ModelForArtists" @click="closeModelForArtists()">Закрыть</button>
</div>
</div>
</div>
</div>
</template>
<script>
import 'axios';
import axios from "axios";
import Album from "@/models/Album";
import Song from "@/models/Song";
import Artist from "@/models/Artist";
export default {
created() {
this.getAlbums();
this.getArtists();
this.getAll();
},
data() {
return{
albums: [],
URL: "http://localhost:8080/",
album: new Album(),
songs: [],
artists: [],
selectedSongs: [],
open: [],
albumId: undefined,
selectedArtists: [],
artistsInAlbum: [],
getAllInfo: new Object() ,
}
},
methods: {
getAll(){
axios.get(this.URL + "album/getAll")
.then(response => {
this.getAllInfo = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
getArtistsInAlbum(id){
axios.get(this.URL + `album/${id}/getAllArtists`)
.then(response => {
this.artistsInAlbum = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
getAlbums(){
axios.get(this.URL + "album")
.then(response => {
this.albums = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
addAlbum(album){
console.log(this.album);
axios.post(this.URL + "album", album)
.then(() => {
this.getAlbums();
this.closeModal();
})
.catch(error => {
console.log(error);
});
},
deleteAlbum(id){
axios.delete(this.URL + `album/${id}`)
.then(() =>{
this.getAlbums();
})
},
editAlbum(album){
axios.put(this.URL + `album/${album.id}`, album)
.then(() =>{
const index = this.albums.findIndex((s) => s.id === album.id);
if (index !== -1) {
this.albums[index] = { ...album };
}
this.closeModal();
this.getAlbums();
})
this.closeModal();
},
openModal(status, album = null) {
if (status === "create") {
this.album = new Album();
this.album.status = "create";
} else if (status === "edit" && album) {
this.album = { ...album };
this.album.status = "edit";
}
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
getSongsFromAlbum(albumId){
this.selectedSongs = [];
axios.get(this.URL + `album/${albumId}/songs`)
.then(response => {
this.songs = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
OpenModelForSongs() {
document.getElementById("ModelForSongs").style.display = "block";
},
closeModelForSongs() {
document.getElementById("ModelForSongs").style.display = "none";
},
OpenModelForArtists() {
document.getElementById("ModelForArtists").style.display = "block";
},
closeModelForArtists() {
document.getElementById("ModelForArtists").style.display = "none";
},
OpenModelForAddSongs(album) {
this.album = { ...album };
document.getElementById("ModalForAddSongs").style.display = "block";
},
CloseModalForAddSongs() {
document.getElementById("ModalForAddSongs").style.display = "none";
},
saveSongs(id) {
axios.post(this.URL + `album/${id}/addSongs`, this.selectedSongs)
.then(() => {
this.getSongsFromAlbum(id);
this.CloseModalForAddSongs();
console.log(this.songs);
})
.catch(error => {
console.log(error);
});
},
getSongsFromUndefinedAlbum(){
axios.get(this.URL + `album/getSongsUndefined`)
.then(response => {
this.songs = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
deleteSongFromAlbum(id){
axios.delete(this.URL + `album/deleteSongFromAlbum/${id}`)
.then(() =>{
this.getSongsFromAlbum();
})
.catch(error => {
console.log(error);
});
},
OpenModelForAddArtists(status, album = null) {
if (status === "create") {
this.album = new Album();
this.album.status = "create";
} else if (status === "edit" && album) {
this.album = { ...album };
this.album.status = "edit";
}
this.open = this.album.artistIds ? [...this.album.artistIds] : []; // Создаём новый массив, чтобы избежать проблем с ссылками
this.loadSelectedArtists(); // Загрузка выбранных альбомов при открытии модального окна
document.getElementById("openModalForAddArtists").style.display = "block";
},
closeModalForAddArtists() {
document.getElementById("openModalForAddArtists").style.display = "none";
this.open = [...this.selectedArtists]; // Обновление массива open значениями из selectedAlbums
this.selectedArtists = []; // Сброс выбранных альбомов
this.album = new Album(); // Сброс текущего предмета при закрытии модального окна
},
loadSelectedArtists() {
// Загрузка выбранных альбомов из массива open
this.selectedArtists = [...this.open];
},
addArtistToAlbum(id, list) {
axios
.post(this.URL + `album/${id}/addArtistToAlbum`, list)
.then(() => {
this.closeModalForAddArtists();
this.getAlbums(); // Обновляем список исполнителей после успешного добавления
this.open = [...this.selectedArtists]; // Обновляем массив выбранных альбомов
})
.catch((error) => {
console.log(error);
});
},
getArtists(){
axios.get(this.URL + "artist")
.then(response => {
this.artists = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
}
}
</script>
<style>
</style>

130
front/src/pages/artists.vue Normal file
View File

@@ -0,0 +1,130 @@
<template>
<div class="container mt-4">
<h1 class="text-center mb-4">Исполнители</h1>
<button class="btn btn-primary mr-2" @click="openModal('create')">Добавить</button>
<table class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>Имя</th>
<th>Жанр</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="art in artists" :key="art.id">
<td>{{ art.artistName }}</td>
<td>{{ art.genre }}</td>
<td>
<td>
<button class="btn btn-primary mr-2" @click="openModal('edit', art)">Изменить</button>
</td>
<td>
<button class="btn btn-danger" @click="deleteArtist(art.id)">Удалить</button>
</td>
</td>
</tr>
</tbody>
</table>
</div>
<!--Форма для создания и добавления исполнителей -->
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Исполнитель</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="artistName">Имя:</label>
<input type="text" class="form-control" id="artistName" name="artistName" v-model="artist.artistName">
</div>
<div class="form-group">
<label for="genre">Жанр:</label>
<input type="text" class="form-control" id="genre" name="genre" v-model="artist.genre">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-primary" v-if="artist.status === 'create'" @click="addArtist(artist)">Создать</button>
<button type="button" class="btn btn-primary" v-else @click="editArtist(artist)">Сохранить</button>
</div>
</div>
</div>
</div>
</template>
<script>
import 'axios';
import axios from "axios";
import Artist from "@/models/Artist";
import Album from "@/models/Album";
export default {
created() {
this.getArtists();
},
data() {
return{
artists: [],
URL: "http://localhost:8080/",
artist: new Artist(),
}
},
methods: {
getArtists(){
axios.get(this.URL + "artist")
.then(response => {
this.artists = response.data;
})
.catch(error => {
console.log(error);
});
},
addArtist(artist){
console.log(artist);
axios.post(this.URL + "artist", artist)
.then(() => {
this.getArtists();
this.closeModal();
})
.catch(error => {
console.log(error);
});
},
deleteArtist(id){
axios.delete(this.URL + `artist/${id}`)
.then(() =>{
this.getArtists();
})
},
editArtist(artist){
axios.put(this.URL + `artist/${artist.id}`, artist)
.then(() =>{
const index = this.artists.findIndex((s) => s.id === artist.id);
if (index !== -1) {
this.artists[index] = { ...artist };
}
this.closeModal();
this.getArtists();
})
this.closeModal();
},
openModal(status, artist = null) {
if (status === "create") {
this.artist = new Artist();
this.artist.status = "create";
} else if (status === "edit" && artist) {
this.artist = { ...artist };
this.artist.status = "edit";
}
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
}
}
</script>
<style>
</style>

156
front/src/pages/songs.vue Normal file
View File

@@ -0,0 +1,156 @@
<template>
<div class="container mt-4">
<h1 class="text-center mb-4">Песни</h1>
<button class="btn btn-primary mr-2" @click="openModal('create')">Добавить</button>
<table class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>Название</th>
<th>Продолжительность</th>
<th>Альбом</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="son in songs" :key="son.id">
<td>{{ son.songName }}</td>
<td>{{ son.duration }}</td>
<td>{{ son.albumName || 'No Album'}}</td>
<td>
<td>
<button class="btn btn-primary mr-2" @click="openModal('edit', son)">Изменить</button>
</td>
<td>
<button class="btn btn-danger" @click="deleteSong(son.id)">Удалить</button>
</td>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Песня</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="songName">Название:</label>
<input type="text" class="form-control" id="songName" name="songName" v-model="editedSong.songName">
</div>
<div class="form-group">
<label for="duration">Продолжительность:</label>
<input type="number" class="form-control" id="duration" name="duration" step="0.1" v-model="editedSong.duration">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-primary" v-if="editedSong.status === 'create'" @click="addSong(editedSong)">Создать</button>
<button type="button" class="btn btn-primary" v-else @click="editSong(editedSong)">Сохранить</button>
</div>
</div>
</div>
</div>
</template>
<script>
import 'axios';
import axios from "axios";
import Song from "@/models/Song";
export default {
created() {
this.getSongs();
this.getAlbums();
},
mounted() {
const addModal = document.getElementById('editModal');
addModal.addEventListener('shown.bs.modal', function () {
})
},
data() {
return{
songs: [],
albums: [],
URL: "http://localhost:8080/",
song: new Song(),
editedSong: new Song(),
}
},
methods: {
getSongs(){
axios.get(this.URL + "song")
.then(response => {
this.songs = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
getAlbums() {
axios.get(this.URL + "song/albums")
.then(response => {
this.albums = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
addSong(song) {
console.log(song);
song.album = null;
console.log(song);
axios
.post(this.URL + "song", song)
.then(() => {
this.getSongs();
this.closeModal();
})
.catch((error) => {
console.log(error);
});
},
deleteSong(id){
axios.delete(this.URL + `song/${id}`)
.then(() =>{
this.getSongs();
})
},
openModal(status, song = null) {
if (status === "create") {
this.editedSong = new Song();
this.editedSong.status = "create";
} else if (status === "edit" && song) {
this.editedSong = { ...song };
this.editedSong.status = "edit";
}
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
editSong(song) {
axios.put(this.URL + `song/${song.id}`, song)
.then(() => {
const index = this.songs.findIndex((s) => s.id === song.id);
if (index !== -1) {
this.songs[index] = { ...song };
}
this.closeModal();
this.getSongs();
})
.catch((error) => {
console.log(error);
});
},
}
}
</script>
<style>
</style>

19
front/src/router/index.js Normal file
View File

@@ -0,0 +1,19 @@
import artists from "../pages/artists.vue"
import albums from "../pages/albums.vue"
import songs from "../pages/songs.vue"
import {createRouter, createWebHistory} from "vue-router"
const routes = [
{path: '/artists', component: artists},
{path: '/albums', component: albums},
{path: '/songs', component: songs},
]
const router = createRouter({
history: createWebHistory(),
linkActiveClass: 'active',
routes
})
export default router;

View File

@@ -0,0 +1,15 @@
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<style>
@media (min-width: 1024px) {
.about {
min-height: 100vh;
display: flex;
align-items: center;
}
}
</style>

View File

@@ -0,0 +1,9 @@
<script setup>
import TheWelcome from '../components/TheWelcome.vue'
</script>
<template>
<main>
<TheWelcome />
</main>
</template>

View File

@@ -0,0 +1,12 @@
package ru.ulstu.is.sbapp.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.sbapp.database.model.Album;
import java.util.List;
public interface IAlbumRepository extends JpaRepository<Album, Long> {
@Query("SELECT a FROM Album a WHERE a.albumName = :name")
List<Album> getAlbumsByName(String name);
}

View File

@@ -0,0 +1,16 @@
package ru.ulstu.is.sbapp.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import java.util.List;
public interface IArtistRepository extends JpaRepository<Artist, Long> {
@Query(value = "SELECT * FROM artist_album", nativeQuery = true)
List<Object[]> getAllArtistAlbum();
@Query("SELECT a FROM Artist a WHERE a.artistName = :name")
List<Artist> getArtistsByName(String name);
}

View File

@@ -0,0 +1,15 @@
package ru.ulstu.is.sbapp.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulstu.is.sbapp.database.model.Song;
import java.util.List;
public interface ISongRepository extends JpaRepository<Song, Long> {
@Query("SELECT a.songs FROM Album a WHERE :song MEMBER OF a.songs")
List<Song> findSongsInAlbum(@Param("song") Song song);
@Query("SELECT s FROM Song s WHERE s.songName = :name")
List<Song> getSongsByName(String name);
}

View File

@@ -2,12 +2,19 @@ package ru.ulstu.is.sbapp;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
class WebConfiguration implements WebMvcConfigurer {
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
public static final String REST_API = "/api";
@Override
public void addViewControllers(ViewControllerRegistry registry) {
WebMvcConfigurer.super.addViewControllers(registry);
registry.addViewController("artist");
}
}

View File

@@ -0,0 +1,82 @@
package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.WebConfiguration;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.service.AlbumService;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/album")
public class AlbumController {
private final AlbumService albumService;
public AlbumController(AlbumService albumService) {
this.albumService = albumService;
}
@GetMapping("/{id}")
public AlbumDTO getAlbum(@PathVariable Long id){
return new AlbumDTO(albumService.findAlbum(id));
}
@GetMapping
public List<AlbumDTO> getAlbums(){
return albumService.findAllAlbums().stream()
.map(AlbumDTO::new)
.toList();
}
@PostMapping
public AlbumDTO createAlbum(@RequestBody @Valid AlbumDTO albumDTO){
return new AlbumDTO(albumService.addAlbum(albumDTO.getAlbumName()));
}
@PutMapping("/{id}")
public AlbumDTO updateAlbum(@PathVariable Long id, @RequestBody @Valid AlbumDTO albumDTO){
return new AlbumDTO(albumService.updateAlbum(id, albumDTO.getAlbumName()));
}
@DeleteMapping("/{id}")
public AlbumDTO deleteAlbum(@PathVariable Long id){
return new AlbumDTO(albumService.deleteAlbum(id));
}
@GetMapping("/{albumId}/songs")
public ResponseEntity<List<Song>> getSongsFromAlbum(@PathVariable Long albumId) {
List<Song> songs = albumService.getSongFromAlbum(albumId);
return ResponseEntity.ok(songs);
}
@GetMapping("/{albumId}/getAllArtists")
public ResponseEntity<List<Artist>> getArtistInAlbum(@PathVariable Long albumId){
List<Artist> artists = albumService.getArtistInAlbum(albumId);
return ResponseEntity.ok(artists);
}
@GetMapping("/getSongsUndefined")
public ResponseEntity<List<Song>> getSongsFromUndefinedAlbum(){
List<Song> songs = albumService.getSongsUndefined();
return ResponseEntity.ok(songs);
}
@PostMapping("/{id}/addSongs")
public void addSongToAlbum(@PathVariable Long id, @RequestBody @Valid List<Long> songsIds){
albumService.addSongToAlbum(id, songsIds);
}
@DeleteMapping("deleteSongFromAlbum/{id}")
public void deleteSongFromAlbum(@PathVariable Long id){
albumService.deleteSongFromAlbum(id);
}
@PostMapping("/{id}/addArtistToAlbum")
public void addArtistToAlbum(@PathVariable Long id, @RequestBody @Valid List<Long> artistIds){
albumService.addArtistToAlbum(id, artistIds);
}
}

View File

@@ -0,0 +1,38 @@
package ru.ulstu.is.sbapp.controllers;
import ru.ulstu.is.sbapp.database.model.Album;
import java.util.List;
public class AlbumDTO {
private Long id;
private String albumName;
private List<Long> artistIds;
public AlbumDTO(){
}
public AlbumDTO(Album album){
this.id = album.getId();
this.albumName = album.getAlbumName();
this.artistIds = album.getArtistIds();
}
public Long getId(){
return id;
}
public String getAlbumName(){
return albumName;
}
public void setId(Long id){
this.id = id;
}
public void setAlbumName(String name){
this.albumName = name;
}
public List<Long> getArtistIds(){
return artistIds;
}
}

View File

@@ -0,0 +1,132 @@
package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.service.AlbumService;
import ru.ulstu.is.sbapp.database.service.ArtistService;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Controller
@RequestMapping("/album")
public class AlbumMvcController {
private final AlbumService albumService;
private final ArtistService artistService;
public AlbumMvcController(AlbumService albumService, ArtistService artistService) {
this.albumService = albumService;
this.artistService = artistService;
}
@GetMapping
public String getAlbums(Model model) {
model.addAttribute("albums",
albumService.findAllAlbums().stream()
.map(AlbumDTO::new)
.toList());
return "album";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editAlbum(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("albumDTO", new AlbumDTO());
} else {
model.addAttribute("albumId", id);
model.addAttribute("albumDTO", new AlbumDTO(albumService.findAlbum(id)));
}
return "album-edit";
}
@PostMapping(value = {"/", "/{id}"})
public String saveAlbum(@PathVariable(required = false) Long id,
@ModelAttribute @Valid AlbumDTO albumDTO,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "album-edit";
}
if (id == null || id <= 0) {
albumService.addAlbum(albumDTO.getAlbumName());
} else {
albumService.updateAlbum(id, albumDTO.getAlbumName());
}
return "redirect:/album";
}
@PostMapping("/delete/{id}")
public String deleteAlbum(@PathVariable Long id) {
albumService.deleteAlbum(id);
return "redirect:/album";
}
@GetMapping("/songs/{id}")
public String getSongsFromAlbum(@PathVariable Long id, Model model) {
List<Song> songs = albumService.getSongFromAlbum(id);
model.addAttribute("songs", songs);
return "view-songs";
}
@GetMapping("/artists/{id}")
public String getArtistsFromAlbum(@PathVariable Long id, Model model) {
List<Artist> artists = albumService.getArtistInAlbum(id);
model.addAttribute("artists", artists);
return "view-artists";
}
@GetMapping("/getSongsUndefined/{id}")
public String getSongsFromUndefinedAlbum(@PathVariable Long id, Model model) {
List<Song> songs = albumService.getSongsUndefined();
model.addAttribute("undefinedSongs", songs);
model.addAttribute("albumId", id);
model.addAttribute("albumDTO", new AlbumDTO(albumService.findAlbum(id)));
return "add-songs-to-album";
}
@PostMapping("/addSongs/{id}")
public String addSongToAlbum(@PathVariable Long id,
@RequestParam("songId") List<String> songsIds) {
List<Long> songIdsAsLong = songsIds.stream()
.map(Long::parseLong)
.collect(Collectors.toList());
albumService.addSongToAlbum(id, songIdsAsLong);
return "redirect:/album";
}
@PostMapping("/deleteSongFromAlbum/{id}")
public String deleteSongFromAlbum(@PathVariable Long id) {
albumService.deleteSongFromAlbum(id);
return "redirect:/album";
}
@GetMapping("/getArtistsUndefined/{id}")
public String getArtistsFromUndefinedAlbum(@PathVariable Long id, Model model) {
List<Artist> artists = albumService.getArtistsUndefined(id);
model.addAttribute("undefinedArtists", artists);
model.addAttribute("albumId", id);
model.addAttribute("albumDTO", new AlbumDTO(albumService.findAlbum(id)));
return "add-artist-to-album";
}
@PostMapping("/addArtists/{id}")
public String addArtistToAlbum(@PathVariable Long id,
@RequestParam("artistId") List<String> artistIds) {
List<Long> artistIdsAsLong = artistIds.stream()
.map(Long::parseLong)
.collect(Collectors.toList());
albumService.addArtistToAlbum(id, artistIdsAsLong);
return "redirect:/album";
}
}

View File

@@ -0,0 +1,55 @@
package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.WebConfiguration;
import ru.ulstu.is.sbapp.database.service.ArtistService;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/artist")
public class ArtistController {
private final ArtistService artistService;
public ArtistController(ArtistService artistService) {
this.artistService = artistService;
}
@GetMapping("/{id}")
public ArtistDTO getArtist(@PathVariable Long id){
return new ArtistDTO(artistService.findArtist(id));
}
@GetMapping
public List<ArtistDTO> getArtist(){
return artistService.findAllArtists().stream()
.map(ArtistDTO::new)
.toList();
}
@PostMapping
public ArtistDTO createArtist(@RequestBody @Valid ArtistDTO artistDTO){
return new ArtistDTO(artistService.addArtist(artistDTO.getArtistName(), artistDTO.getGenre()));
}
@PutMapping("/{id}")
public ArtistDTO updateArtist(@PathVariable Long id, @RequestBody @Valid ArtistDTO artistDTO){
return new ArtistDTO(artistService.updateArtist(id, artistDTO.getArtistName(), artistDTO.getGenre()));
}
@DeleteMapping("/{id}")
public ArtistDTO deleteArtist(@PathVariable Long id){
return new ArtistDTO(artistService.deleteArtist(id));
}
@GetMapping("/getAllArtistAlbum")
public List<Object[]> getAllArtistAlbum(){
return artistService.getAllArtistAlbum();
}
@PostMapping("/{id}/addArtistToAlbum")
public void addArtistToAlbum(@PathVariable Long id, @RequestBody @Valid List<Long> groupsIds){
artistService.addArtistToAlbum(id, groupsIds);
}
}

View File

@@ -0,0 +1,48 @@
package ru.ulstu.is.sbapp.controllers;
import ru.ulstu.is.sbapp.database.model.Artist;
import java.util.List;
public class ArtistDTO {
private Long id;
private String artistName;
private String genre;
private List<Long> albumIds;
public ArtistDTO(){
}
public ArtistDTO(Artist artist){
this.id = artist.getId();
this.artistName = artist.getArtistName();
this.genre = artist.getGenre();
this.albumIds = artist.getAlbumIds();
}
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
public String getArtistName(){
return artistName;
}
public String getGenre(){
return genre;
}
public void setGenre(String genre){
this.genre = genre;
}
public void setArtistName(String artistName){
this.artistName = artistName;
}
public List<Long> getAlbumIds(){
return albumIds;
}
}

View File

@@ -0,0 +1,84 @@
package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.database.service.AlbumService;
import ru.ulstu.is.sbapp.database.service.ArtistService;
import java.util.List;
@Controller
@RequestMapping("/artist")
public class ArtistMvcController {
private final ArtistService artistService;
private final AlbumService albumService;
public ArtistMvcController(ArtistService artistService, AlbumService albumService)
{
this.artistService = artistService;
this.albumService = albumService;
}
@GetMapping
public String getArtists(Model model) {
model.addAttribute("artists",
artistService.findAllArtists().stream()
.map(ArtistDTO::new)
.toList());
return "artist";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editArtist(@PathVariable(required = false) Long id,
Model model) {
if (id == null || id <= 0) {
model.addAttribute("artistDTO", new ArtistDTO());
} else {
model.addAttribute("artistId", id);
model.addAttribute("artistDTO", new ArtistDTO(artistService.findArtist(id)));
}
return "artist-edit";
}
@PostMapping(value = {"/", "/{id}"})
public String saveArtist(@PathVariable(required = false) Long id,
@ModelAttribute @Valid ArtistDTO artistDTO,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "artist-edit";
}
if (id == null || id <= 0) {
artistService.addArtist(artistDTO.getArtistName(), artistDTO.getGenre());
} else {
artistService.updateArtist(id, artistDTO.getArtistName(), artistDTO.getGenre());
}
return "redirect:/artist";
}
@PostMapping("/delete/{id}")
public String deleteArtist(@PathVariable Long id) {
artistService.deleteArtist(id);
return "redirect:/artist";
}
@GetMapping("/addArtistToAlbum/{id}")
public String addArtistToAlbumForm(@PathVariable Long id, Model model) {
model.addAttribute("artistDTO", new ArtistDTO(artistService.findArtist(id)));
model.addAttribute("artistId", id);
model.addAttribute("albums", albumService.findAllAlbums());
return "add-artist-to-album";
}
@PostMapping("/addArtistToAlbum/{id}")
public String addArtistToAlbum(@PathVariable Long id,
@RequestParam("albumId") List<Long> albumIds) {
artistService.addArtistToAlbum(id, albumIds);
return "redirect:/artist";
}
}

View File

@@ -0,0 +1,26 @@
package ru.ulstu.is.sbapp.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.sbapp.WebConfiguration;
import ru.ulstu.is.sbapp.database.service.SearchService;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/search")
public class SearchController {
private final SearchService searchService;
public SearchController(SearchService searchService) {
this.searchService = searchService;
}
@GetMapping
public Map<String, List<Object>> getByName(@RequestParam(value = "name", defaultValue = "песня") String name) {
return searchService.getByName(name);
}
}

View File

@@ -0,0 +1,32 @@
package ru.ulstu.is.sbapp.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ru.ulstu.is.sbapp.database.service.SearchService;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/search")
public class SearchMvcController {
private final SearchService searchService;
public SearchMvcController(SearchService searchService) {
this.searchService = searchService;
}
@GetMapping
public String getByName(@RequestParam(value = "name", defaultValue = "песня") String name, Model model) {
Map<String, List<Object>> searchResult = searchService.getByName(name);
model.addAttribute("name", name);
model.addAttribute("searchResult", searchResult != null);
if (searchResult != null) {
model.addAttribute("songs", searchResult.get("songs"));
model.addAttribute("albums", searchResult.get("albums"));
model.addAttribute("artists", searchResult.get("artists"));
}
return "search";
}
}

View File

@@ -0,0 +1,55 @@
package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.WebConfiguration;
import ru.ulstu.is.sbapp.database.service.AlbumService;
import ru.ulstu.is.sbapp.database.service.SongService;
import java.util.List;
@RestController
@RequestMapping(WebConfiguration.REST_API + "/song")
public class SongController {
private final SongService songService;
private final AlbumService albumService;
public SongController(SongService songService, AlbumService albumService) {
this.songService = songService;
this.albumService = albumService;
}
@GetMapping("/{id}")
public SongDTO getSong(@PathVariable Long id){
return new SongDTO(songService.findSong(id));
}
@GetMapping
public List<SongDTO> getSongs(){
return songService.findAllSongs().stream()
.map(SongDTO::new)
.toList();
}
@PostMapping
public SongDTO createSong(@RequestBody @Valid SongDTO songDTO){
return new SongDTO(songService.addSong(songDTO.getSongName(), songDTO.getDuration()));
}
@PutMapping("/{id}")
public SongDTO updateSong(@PathVariable Long id, @RequestBody @Valid SongDTO songDTO) {
return new SongDTO(songService.updateSong(id, songDTO.getSongName(), songDTO.getDuration()));
}
@DeleteMapping("/{id}")
public SongDTO deleteSong(@PathVariable Long id){
return new SongDTO(songService.deleteSong(id));
}
@GetMapping("/albums")
public List<AlbumDTO> getAlbums() {
return albumService.findAllAlbums().stream()
.map(AlbumDTO::new)
.toList();
}
}

View File

@@ -0,0 +1,57 @@
package ru.ulstu.is.sbapp.controllers;
import ru.ulstu.is.sbapp.database.model.Song;
public class SongDTO {
private Long id;
private String songName;
private Double duration;
private Long albumId;
private String albumName;
public SongDTO() {
}
public SongDTO(Song song) {
this.id = song.getId();
this.songName = song.getSongName();
this.duration = song.getDuration();
if(song.getAlbum() != null){
this.albumName = song.getAlbum().getAlbumName();
}
}
public String getAlbumName() {
return albumName;
}
public Long getId(){
return id;
}
public String getSongName(){
return songName;
}
public Double getDuration(){
return duration;
}
public Long getAlbumId(){
return albumId;
}
public void setAlbumId(Long id){
this.albumId = id;
}
public void setId(Long id){
this.id = id;
}
public void setSongName(String name){
this.songName = name;
}
public void setDuration(Double duration){
this.duration = duration;
}
}

View File

@@ -0,0 +1,67 @@
package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.database.service.AlbumService;
import ru.ulstu.is.sbapp.database.service.SongService;
@Controller
@RequestMapping("/song")
public class SongMvcController {
private final SongService songService;
private final AlbumService albumService;
public SongMvcController(SongService songService, AlbumService albumService)
{
this.songService = songService;
this.albumService = albumService;
}
@GetMapping
public String getSongs(Model model) {
model.addAttribute("songs",
songService.findAllSongs().stream()
.map(SongDTO::new)
.toList());
return "song";
}
@GetMapping(value = {"/edit", "/edit/{id}"})
public String editSong(@PathVariable(required = false) Long id,
Model model) {
model.addAttribute("Albums", albumService.findAllAlbums());
if (id == null || id <= 0) {
model.addAttribute("songDTO", new SongDTO());
} else {
model.addAttribute("songId", id);
model.addAttribute("songDTO", new SongDTO(songService.findSong(id)));
}
return "song-edit";
}
@PostMapping(value = {"/", "/{id}"})
public String saveSong(@PathVariable(required = false) Long id,
@ModelAttribute @Valid SongDTO songDTO,
BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
model.addAttribute("errors", bindingResult.getAllErrors());
return "song-edit";
}
if (id == null || id <= 0) {
songService.addSong(songDTO.getSongName(), songDTO.getDuration());
} else {
songService.updateSong(id, songDTO.getSongName(), songDTO.getDuration());
}
return "redirect:/song";
}
@PostMapping("/delete/{id}")
public String deleteSong(@PathVariable Long id) {
songService.deleteSong(id);
return "redirect:/song";
}
}

View File

@@ -1,80 +1,44 @@
package ru.ulstu.is.sbapp.database.model;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "album")
@Table(name = "albums")
public class Album {
@Id
@GeneratedValue
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String albumName;
@OneToMany(cascade = {CascadeType.MERGE})
@JoinColumn(name = "songs", nullable = true)
@JsonManagedReference
@OneToMany(fetch = FetchType.EAGER, mappedBy = "album")
private List<Song> songs;
@ManyToMany(cascade = { CascadeType.MERGE }, fetch = FetchType.EAGER)
@JoinTable(name = "albums_artists",
joinColumns = @JoinColumn(name = "album_fk"),
inverseJoinColumns = @JoinColumn(name = "artist_fk"))
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "artist_album",
joinColumns = {@JoinColumn(name = "album_id")},
inverseJoinColumns = {@JoinColumn(name = "artist_id")})
private List<Artist> artists;
public Album(){
}
public Album(String albumName){
this.albumName = albumName;
}
public Long getId() {
return id;
public Album() {
this.songs = new ArrayList<>();
}
public String getAlbumName() {
return albumName;
}
public void setAlbumName(String albumName) {
this.albumName = albumName;
}
public List<Artist> getArtists() {
return artists;
}
public List<Song> getSongs(){return songs;}
public void setArtists(List<Artist> artists) {
this.artists = artists;
}
public void update(Album album){
this.albumName = album.albumName;
this.artists = album.getArtists();
}
public void addArtist(Artist artist){
if (artists == null){
this.artists = new ArrayList<>();
}
if (!artists.contains(artist)) {
this.artists.add(artist);
artist.addAlbum(this);
}
}
public void removeArtist(Artist artist){
if (artists.contains(artist)) {
this.artists.remove(artist);
artist.removeAlbum(this);
}
}
public void addSong(Song song){
if (songs == null){
this.songs = new ArrayList<>();
}
if (!songs.contains(song)) {
this.songs.add(song);
song.setAlbum(this);
}
}
public void removeSong(Song song){
if (songs.contains(song))
this.songs.remove(song);
public Album(String name) {
this.albumName = name;
this.songs = new ArrayList<>();
}
public Long getId() { return id; }
public String getAlbumName() { return albumName; }
public void setAlbumName(String name) { this.albumName = name; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
@@ -92,7 +56,48 @@ public class Album {
public String toString() {
return "Album{" +
"id=" + id +
", albumName='" + albumName + '\'' +
", name='" + albumName + '\'' +
'}';
}
public void setSong(Song song){
this.songs.add(song);
if(song.getAlbum() != this){
song.setAlbum(this);
}
}
public List<Song> getSongs(){
return songs;
}
public void setSongs(List<Song> songs) {
this.songs = songs;
}
public List<Artist> getArtists(){
return artists;
}
public void setArtists(List<Artist> artists) {
this.artists = artists;
}
public void addArtist(Artist artist) {
artists.add(artist);
artist.getAlbums().add(this);
}
public List<Long> getArtistIds() {
if (artists.isEmpty()) {
return Collections.emptyList();
} else {
List<Long> artistIds = new ArrayList<>();
for (Artist artist : artists) {
if (!artistIds.contains(artist.getId())) {
artistIds.add(artist.getId());
}
}
return artistIds;
}
}
}

View File

@@ -1,69 +1,41 @@
package ru.ulstu.is.sbapp.database.model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "artists")
public class Artist {
@Id
@GeneratedValue
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String artistName;
@Column(name = "genre")
private String genre;
@ManyToMany(mappedBy = "artists", cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
private List<Album> album;
@JsonBackReference
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
@JoinTable(name = "artist_album",
joinColumns = {@JoinColumn(name = "artist_id")},
inverseJoinColumns = {@JoinColumn(name = "album_id")})
private List<Album> albums = new ArrayList<>();
public Artist() {
}
public Artist(String artistName, String genre) {
this.artistName = artistName;
public Artist(String name, String genre) {
this.artistName = name;
this.genre = genre;
}
public Long getId() {
return id;
}
public String getArtistName() {
return artistName;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public List<Album> getAlbum() {
return album;
}
public void setAlbum(List<Album> album) {
this.album = album;
}
public void addAlbum(Album album) {
if (this.album == null) {
this.album = new ArrayList<>();
}
if (!this.album.contains(album))
this.album.add(album);
}
public void removeAlbum(Album album) {
if (this.album.contains(album))
this.album.remove(album);
}
public Long getId() { return id; }
public String getArtistName() { return artistName; }
public void setArtistName(String name) { this.artistName = name; }
public String getGenre() { return genre; }
public void setGenre(String genre) { this.genre = genre; }
@Override
public boolean equals(Object o) {
@@ -82,8 +54,29 @@ public class Artist {
public String toString() {
return "Artist{" +
"id=" + id +
", artistName='" + artistName + '\'' +
", genre='" + genre + '\'' +
", name='" + artistName + '\'' +
'}';
}
public List<Album> getAlbums(){
return albums;
}
public void setAlbums(List<Album> albums) {
this.albums = albums;
}
public List<Long> getAlbumIds() {
if (albums.isEmpty()) {
return Collections.emptyList();
} else {
List<Long> albumIds = new ArrayList<>();
for (Album album : albums) {
if (!albumIds.contains(album.getId())) {
albumIds.add(album.getId());
}
}
return albumIds;
}
}
}

View File

@@ -1,55 +1,48 @@
package ru.ulstu.is.sbapp.database.model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.util.Objects;
@Entity
@Table(name = "song")
@Table(name = "songs")
public class Song {
@Id
@GeneratedValue
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String songName;
@Column(name = "duration")
private Double duration;
@ManyToOne(cascade = {CascadeType.MERGE}, fetch = FetchType.EAGER)
@JoinColumn(name = "album", nullable = true)
@JsonBackReference
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "album_id", nullable = true)
private Album album;
public Song(){
public Song() {
}
public Song(String songName, Double duration){
public Song(String songName, Double duration) {
this.songName = songName;
this.duration = duration;
}
public Long getId(){return id;}
public String getSongName(){
return songName;
}
public Double getSongDuration(){
return duration;
}
public void setSongName(String songName) {
this.songName = songName;
}
public Long getId() { return id; }
public String getSongName() { return songName; }
public void setSongName(String songName) { this.songName = songName; }
public Double getDuration() { return duration;}
public void setDuration(Double duration) { this.duration = duration; }
public void setSongDuration(Double duration) {
this.duration = duration;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Song song = (Song) o;
return Objects.equals(id, song.id);
}
public Album getAlbum(){
return album;
}
public void setAlbum(Album album){
this.album = album;
}
@Override
public int hashCode() {
return Objects.hash(id);
@@ -57,10 +50,29 @@ public class Song {
@Override
public String toString() {
String albumStr = (album != null) ? album.getAlbumName() : "No Album";
return "Song{" +
"id=" + id +
", songName='" + songName + '\'' +
", duration='" + duration + '\'' +
", album='" + albumStr + '\'' +
'}';
}
public Album getAlbum() {
return album;
}
public void setAlbum(Album album) {
if (this.album != album) {
if (this.album != null) {
this.album.getSongs().remove(this);
}
this.album = album;
if (album != null && !album.getSongs().contains(this)) {
album.getSongs().add(this);
}
}
}
}

View File

@@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.database.service;
public class AlbumNotFoundException extends RuntimeException{
public AlbumNotFoundException(Long id){
super(String.format("Album with id [%s] is not found", id));
}
}

View File

@@ -1,133 +1,140 @@
package ru.ulstu.is.sbapp.database.service;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.is.sbapp.Repository.IAlbumRepository;
import ru.ulstu.is.sbapp.database.model.Album;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.model.Album;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class AlbumService {
@PersistenceContext
private EntityManager em;
private final IAlbumRepository albumRepository;
private final SongService songService;
private final ArtistService artistService;
public AlbumService(IAlbumRepository albumRepository, SongService songService, @Lazy ArtistService artistService) {
this.albumRepository = albumRepository;
this.songService = songService;
this.artistService = artistService;
}
@Transactional
public Album addAlbum(String name) {
public Album addAlbum(String name){
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Album name is null or empty");
}
final Album album = new Album(name);
em.persist(album);
return album;
return albumRepository.save(album);
}
@Transactional
public Album addSong(Album currentAlbum, List<Song> songs){
for (Song song : songs) {
if (song.getAlbum() != null) {
song.getAlbum().removeSong(song);
}
currentAlbum.addSong(song);
em.merge(song);
}
em.merge(currentAlbum);
return currentAlbum;
}
@Transactional
public Album addArtist(Album currentAlbum, List<Artist> artists){
for (Artist artist : artists) {
currentAlbum.addArtist(artist);
}
em.merge(currentAlbum);
return currentAlbum;
}
@Transactional(readOnly = true)
public Album findAlbum(Long id) {
final Album album = em.find(Album.class, id);
if (album == null) {
throw new EntityNotFoundException(String.format("Album with id [%s] is not found", id));
}
return album;
@Transactional(readOnly = true)
public Album findAlbum(Long id){
final Optional<Album> album = albumRepository.findById(id);
return album.orElseThrow(() -> new AlbumNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Album> findAllAlbums() {
return em.createQuery("select s from Album s", Album.class)
.getResultList();
return albumRepository.findAll();
}
@Transactional
public Album updateAlbum(Long id, String name, List<Song> newSongs, List<Artist> newArtists) {
public Album updateAlbum(Long id, String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Album name is null or empty");
}
final Album currentAlbum = findAlbum(id);
currentAlbum.setAlbumName(name);
em.merge(currentAlbum);
if(newSongs != null){
for (Song newSong : newSongs) {
if (!currentAlbum.getSongs().contains(newSong)) {
currentAlbum.addSong(newSong);
}
}
for(int i = 0; i < currentAlbum.getSongs().size(); i++) {
if (!newSongs.contains(currentAlbum.getSongs().get(i))) {
currentAlbum.removeSong(currentAlbum.getSongs().get(i));
}
}
}
for (Artist newArtist : newArtists) {
if (!currentAlbum.getArtists().contains(newArtist)) {
currentAlbum.addArtist(newArtist);
}
}
for(int i = 0; i < currentAlbum.getArtists().size(); i++){
if(!newArtists.contains(currentAlbum.getArtists().get(i))){
currentAlbum.removeArtist(currentAlbum.getArtists().get(i));
}
}
em.merge(currentAlbum);
return currentAlbum;
return albumRepository.save(currentAlbum);
}
@Transactional
public Album deleteAlbum(Long id) {
final Album currentAlbum = findAlbum(id);
List<Artist> artists = currentAlbum.getArtists();
for (Artist artist : artists) {
Artist temp = artist;
currentAlbum.removeArtist(temp);
}
final List<Song> songs = currentAlbum.getSongs();
for (Song song : songs) {
song.setAlbum(null);
}
em.remove(currentAlbum);
return null;
albumRepository.delete(currentAlbum);
return currentAlbum;
}
@Transactional
public void deleteAllAlbums() {
List<Album> list = em.createQuery("select s from Album s", Album.class).getResultList();
for(int i = 0; i < list.size(); i++){
deleteAlbum(list.get(i).getId());
}
em.createQuery("update Song s SET s.album = null ").executeUpdate();
em.createQuery("delete from Album").executeUpdate();
albumRepository.deleteAll();
}
@Transactional
public List<Album> findFilteredAlbum(Long[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("Array id is empty");
public List<Song> getSongFromAlbum(Long albumId){
Optional<Album> albumOptional = albumRepository.findById(albumId);
if (albumOptional.isPresent()) {
Album album = albumOptional.get();
return album.getSongs();
} else {
throw new IllegalArgumentException("Album not found with id: " + albumId);
}
List<Album> albumList = new ArrayList<>();
for (Long aLong : arr) {
albumList.add(em.find(Album.class, aLong));
}
@Transactional
public List<Artist> getArtistInAlbum(Long albumId){
Optional<Album> albumOptional = albumRepository.findById(albumId);
if (albumOptional.isPresent()) {
Album album = albumOptional.get();
return album.getArtists();
} else {
throw new IllegalArgumentException("Album not found with id: " + albumId);
}
return albumList;
}
@Transactional
public List<Song> getSongsUndefined(){
List<Song> songs = new ArrayList<>();
for(Song song : songService.findAllSongs()){
if(song.getAlbum() == null){
songs.add(song);
}
}
return songs;
}
@Transactional
public void addSongToAlbum(Long albumId, List<Long> songIds){
final Album currentAlbum = findAlbum(albumId);
for(Long songId : songIds) {
songService.findSong(songId).setAlbum(currentAlbum);
}
albumRepository.save(currentAlbum);
}
@Transactional
public void deleteSongFromAlbum(Long id){
songService.findSong(id).setAlbum(null);
}
@Transactional
public void addArtistToAlbum(Long albumId, List<Long> artistIds){
final Album currentAlbum = findAlbum(albumId);
currentAlbum.setArtists(new ArrayList<>());
for(Long artistId : artistIds) {
currentAlbum.getArtists().add(artistService.findArtist(artistId));
}
albumRepository.save(currentAlbum);
}
@Transactional
public List<Artist> getArtistsUndefined(Long albumId){
List<Artist> artists = new ArrayList<>();
for(Artist artist : artistService.findAllArtists()){
if(!artist.getAlbumIds().contains(albumId)){
artists.add(artist);
}
}
return artists;
}
}

View File

@@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.database.service;
public class ArtistNotFoundException extends RuntimeException{
public ArtistNotFoundException(Long id){
super(String.format("Artist with id [%s] is not found", id));
}
}

View File

@@ -3,90 +3,79 @@ package ru.ulstu.is.sbapp.database.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.is.sbapp.Repository.IArtistRepository;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.model.Album;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class ArtistService {
@PersistenceContext
private EntityManager em;
private final IArtistRepository artistRepository;
private final AlbumService albumService;
public ArtistService(IArtistRepository artistRepository, AlbumService albumService) {
this.artistRepository = artistRepository;
this.albumService = albumService;
}
@Transactional
public Artist addArtist(String name, String genre) {
if (!StringUtils.hasText(name) || !StringUtils.hasText(genre)) {
throw new IllegalArgumentException("Artist name and genre are null or empty");
public Artist addArtist(String artistName, String genre){
if (!StringUtils.hasText(artistName) || !StringUtils.hasText(genre)) {
throw new IllegalArgumentException("Artist name or genre is null or empty");
}
final Artist artist = new Artist(name, genre);
em.persist(artist);
return artist;
final Artist artist = new Artist(artistName, genre);
return artistRepository.save(artist);
}
@Transactional(readOnly = true)
public Artist findArtist(Long id) {
final Artist artist = em.find(Artist.class, id);
if (artist == null) {
throw new EntityNotFoundException(String.format("Artist with id [%s] is not found", id));
}
return artist;
@Transactional(readOnly = true)
public Artist findArtist(Long id){
final Optional<Artist> artist = artistRepository.findById(id);
return artist.orElseThrow(() -> new ArtistNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Artist> findAllArtists() {
return em.createQuery("select s from Artist s", Artist.class)
.getResultList();
}
@Transactional(readOnly = true)
public List<Artist> findFilteredArtist(Long[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("Array id is empty");
}
List<Artist> artistsList = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
artistsList.add(em.find(Artist.class, arr[i]));
}
return artistsList;
return artistRepository.findAll();
}
@Transactional
public Artist updateArtist(Long id, String name, String genre) {
if (!StringUtils.hasText(name) || !StringUtils.hasText(genre)) {
throw new IllegalArgumentException("Artist name and genre is null or empty");
throw new IllegalArgumentException("Artist name or genre is null or empty");
}
final Artist currentArtist = findArtist(id);
currentArtist.setArtistName(name);
currentArtist.setGenre(genre);
em.merge(currentArtist);
return currentArtist;
return artistRepository.save(currentArtist);
}
@Transactional
public Artist deleteArtist(Long id) {
final Artist currentArtist = findArtist(id);
int size = currentArtist.getAlbum().size();
for (int i = 0; i < size; i++) {
Album temp = currentArtist.getAlbum().get(i);
temp.removeArtist(currentArtist);
currentArtist.removeAlbum(temp);
em.remove(temp);
}
em.remove(currentArtist);
currentArtist.getAlbums().clear(); // Удаляем все связи с альбомами
artistRepository.delete(currentArtist);
return currentArtist;
}
@Transactional
public List<Song> findAllSongsProducedArtist(Artist currentArtist){
if(currentArtist.getAlbum().size() == 0){
throw new IllegalArgumentException("Artist doesn`t produced");
}
List songList = em.createQuery("SELECT DISTINCT a.songs FROM Album a where :artistAlbum MEMBER OF a.artists")
.setParameter("artistAlbum", currentArtist).getResultList();
return songList;
}
@Transactional
public void deleteAllArtists() {
em.createQuery("delete from Artist").executeUpdate();
artistRepository.deleteAll();
}
@Transactional
public List<Object[]> getAllArtistAlbum(){
return artistRepository.getAllArtistAlbum();
}
@Transactional
public void addArtistToAlbum(Long artistId, List<Long> albumIds){
final Artist currentArtist = findArtist(artistId);
currentArtist.setAlbums(new ArrayList<>());
for(Long albumId : albumIds) {
currentArtist.getAlbums().add(albumService.findAlbum(albumId));
}
artistRepository.save(currentArtist);
}
}

View File

@@ -0,0 +1,49 @@
package ru.ulstu.is.sbapp.database.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ulstu.is.sbapp.Repository.IAlbumRepository;
import ru.ulstu.is.sbapp.Repository.IArtistRepository;
import ru.ulstu.is.sbapp.Repository.ISongRepository;
import ru.ulstu.is.sbapp.database.model.Album;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class SearchService {
private final IAlbumRepository albumRepository;
private final ISongRepository songRepository;
private final IArtistRepository artistRepository;
public SearchService(IAlbumRepository albumRepository, ISongRepository songRepository, IArtistRepository artistRepository) {
this.albumRepository = albumRepository;
this.songRepository = songRepository;
this.artistRepository = artistRepository;
}
@Transactional
public Map<String, List<Object>> getByName(String name) {
Map<String, List<Object>> resultMap = new HashMap<>();
List<Song> songs = songRepository.getSongsByName(name).stream().toList();
List<Object> songsResult = new ArrayList<>(songs);
resultMap.put("songs", songsResult);
List<Album> albums = albumRepository.getAlbumsByName(name).stream().toList();
List<Object> albumsResult = new ArrayList<>(albums);
resultMap.put("albums", albumsResult);
List<Artist> artists = artistRepository.getArtistsByName(name).stream().toList();
List<Object> artistsResult = new ArrayList<>(artists);
resultMap.put("artists", artistsResult);
return resultMap;
}
}

View File

@@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.database.service;
public class SongNotFoundException extends RuntimeException {
public SongNotFoundException(Long id){
super(String.format("Song with id [%s] is not found", id));
}
}

View File

@@ -1,87 +1,77 @@
package ru.ulstu.is.sbapp.database.service;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.is.sbapp.Repository.ISongRepository;
import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.model.Album;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class SongService {
@PersistenceContext
private EntityManager em;
private final ISongRepository songRepository;
private final AlbumService albumService;
public SongService(ISongRepository songRepository, @Lazy AlbumService albumService) {
this.songRepository = songRepository;
this.albumService = albumService;
}
@Transactional
public Song addSong(String songName, Double duration) {
if (!StringUtils.hasText(songName) || duration <= 0) {
throw new IllegalArgumentException("Song name is null or empty");
public Song addSong(String songName, Double duration){
if (!StringUtils.hasText(songName) || duration == null) {
throw new IllegalArgumentException("Song name or duration is null or empty");
}
final Song song = new Song(songName, duration);
em.persist(song);
return song;
return songRepository.save(song);
}
@Transactional(readOnly = true)
@Transactional(readOnly = true)
public Song findSong(Long id) {
final Song song = em.find(Song.class, id);
if (song == null) {
throw new EntityNotFoundException(String.format("Song with id [%s] is not found", id));
}
return song;
final Optional<Song> song = songRepository.findById(id);
return song.orElseThrow(() -> new SongNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Song> findAllSongs() {
return em.createQuery("select s from Song s", Song.class)
.getResultList();
return songRepository.findAll();
}
@Transactional
public Song updateSong(Long id, String songName, Double duration, Album album) {
if (!StringUtils.hasText(songName) || duration <= 0) {
throw new IllegalArgumentException("Song name is null or empty");
public Song updateSong(Long id, String name, Double duration) {
if (!StringUtils.hasText(name) || duration == null) {
throw new IllegalArgumentException("Song name or duration is null or empty");
}
final Song currentSong = findSong(id);
currentSong.setSongName(songName);
currentSong.setSongDuration(duration);
currentSong.setAlbum(album);
em.merge(currentSong);
return currentSong;
currentSong.setSongName(name);
currentSong.setDuration(duration);
return songRepository.save(currentSong);
}
@Transactional
public Song deleteSong(Long id) {
final Song currentSong= findSong(id);
if(currentSong.getAlbum() != null) currentSong.getAlbum().removeSong(currentSong);
em.remove(currentSong);
final Song currentSong = findSong(id);
songRepository.delete(currentSong);
return currentSong;
}
@Transactional(readOnly = true)
public List<Song> findFilteredSongs(Long[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("Array id is empty");
}
List<Song> songList = new ArrayList<>();
for (Long aLong : arr) {
songList.add(em.find(Song.class, aLong));
}
return songList;
}
@Transactional
public List findSongsInAlbum(Song currentSong){
if(currentSong.getAlbum() == null){
throw new IllegalArgumentException("Album is empty");
}
return em.createQuery("SELECT s.songs FROM Album s where s.id = :songAlbum")
.setParameter("songAlbum", currentSong.getAlbum().getId()).getResultList();
public void deleteAllSong() {
songRepository.deleteAll();
}
@Transactional
public void deleteAllSongs() {
em.createQuery("delete from Song").executeUpdate();
}
// @Transactional
// public void AddSongToAlbum(Long idSong, Long idAlbum){
// Song song = findSong(idSong);
// Album album = em.find(Album.class, idAlbum);
// if (album == null || song == null) {
// throw new EntityNotFoundException("Album or Song not found");
// }
// song.setAlbum(album);
// em.merge(song);
// }
}

View File

@@ -0,0 +1,43 @@
package ru.ulstu.is.sbapp.database.util.error;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.sbapp.database.service.AlbumNotFoundException;
import ru.ulstu.is.sbapp.database.service.ArtistNotFoundException;
import ru.ulstu.is.sbapp.database.service.SongNotFoundException;
import ru.ulstu.is.sbapp.database.util.validation.ValidationException;
import java.util.stream.Collectors;
@ControllerAdvice(annotations = RestController.class)
public class AdviceController {
@ExceptionHandler({
AlbumNotFoundException.class,
ArtistNotFoundException.class,
SongNotFoundException.class,
ValidationException.class
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleBindException(MethodArgumentNotValidException e) {
final ValidationException validationException = new ValidationException(
e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toSet()));
return handleException(validationException);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleUnknownException(Throwable e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@@ -0,0 +1,9 @@
package ru.ulstu.is.sbapp.database.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException {
public ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
}

View File

@@ -0,0 +1,30 @@
package ru.ulstu.is.sbapp.database.util.validation;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.util.stream.Collectors;
@Component
public class ValidatorUtil {
private final Validator validator;
public ValidatorUtil() {
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
this.validator = factory.getValidator();
}
}
public <T> void validate(T object) {
final Set<ConstraintViolation<T>> errors = validator.validate(object);
if (!errors.isEmpty()) {
throw new ValidationException(errors.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toSet()));
}
}
}

View File

@@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/album/addArtists/{id}(id=${albumId})}" method="post">
<div class="mb-3">
<label for="albumName" class="form-label">Название</label>
<input type="text" class="form-control" id="albumName" th:field="${albumDTO.albumName}" readonly>
</div>
<div class="form-group">
<label for="albumName">Выберите исполнителей для добавления:</label>
<ul class="list-group">
<li class="list-group-item" th:each="artist, iterator: ${undefinedArtists}">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="artistId" th:value="${artist.id}">
<label class="form-check-label" th:text="${artist.artistName}"></label>
</div>
</li>
</ul>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span>Добавить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/album}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/album/addSongs/{id}(id=${albumId})}" method="post">
<div class="mb-3">
<label for="albumName" class="form-label">Название</label>
<input type="text" class="form-control" id="albumName" th:field="${albumDTO.albumName}" readonly>
</div>
<div class="form-group">
<label for="albumName">Выберите песни:</label>
<ul class="list-group">
<li class="list-group-item" th:each="song, iterator: ${undefinedSongs}">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="songId" th:value="${song.id}">
<label class="form-check-label" th:text="${song.songName}"></label>
</div>
</li>
</ul>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span>Добавить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/album}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/album/{id}(id=${id})}" th:object="${albumDTO}" method="post">
<div class="mb-3">
<label for="albumName" class="form-label">Название</label>
<input type="text" class="form-control" id="albumName" th:field="${albumDTO.albumName}" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${albumId == null}">Добавить</span>
<span th:if="${albumId != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/album}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@@ -0,0 +1,56 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<body>
<div layout:fragment="content">
<h1 class="text-center mb-4">Альбомы</h1>
<div>
<a class="btn btn-success button-fixed"
th:href="@{/album/edit}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="album, iterator: ${albums}">
<td th:text="${album.albumName}"></td>
<td>
<div class="btn-album" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/album/edit/{id}(id=${album.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${album.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
<a class="btn btn-primary button-fixed button-sm"
th:href="@{/album/songs/{id}(id=${album.id})}">Посмотреть песни</a>
<a class="btn btn-primary button-fixed button-sm"
th:href="@{/album/getSongsUndefined/{id}(id=${album.id})}">Добавить песни</a>
<a class="btn btn-primary button-fixed button-sm"
th:href="@{/album/getArtistsUndefined/{id}(id=${album.id})}"> Добавить исполнителей</a>
<a class="btn btn-primary button-fixed button-sm"
th:href="@{/album/artists/{id}(id=${album.id})}">Посмотреть исполнителей</a>
</div>
<form th:action="@{/album/delete/{id}(id=${album.id})}" method="post">
<button th:id="'remove-' + ${album.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/artist/{id}(id=${id})}" th:object="${artistDTO}" method="post">
<div class="mb-3">
<label for="artistName" class="form-label">Имя</label>
<input type="text" class="form-control" id="artistName" th:field="${artistDTO.artistName}" required="true">
<label for="genre" class="form-label">Жанр</label>
<input type="text" class="form-control" id="genre" th:field="${artistDTO.genre}" required="true">
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${artistId == null}">Добавить</span>
<span th:if="${artistId != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/artist}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@@ -0,0 +1,50 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<body>
<div layout:fragment="content">
<h1 class="text-center mb-4">Исполнители</h1>
<div>
<a class="btn btn-success button-fixed"
th:href="@{/artist/edit}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Имя</th>
<th scope="col">Жанр</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="artist, iterator: ${artists}">
<td th:text="${artist.artistName}"></td>
<td th:text="${artist.genre}"></td>
<td>
<div class="btn-album" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/artist/edit/{id}(id=${artist.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${artist.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/artist/delete/{id}(id=${artist.id})}" method="post">
<button th:id="'remove-' + ${artist.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,41 @@
<!DOCTYPE html>
<html lang="ru"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Streaming Service</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="icon" href="/favicon.svg">
<script type="text/javascript" src="/webjars/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="/webjars/bootstrap/5.1.3/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/webjars/font-awesome/6.1.0/css/all.min.css"/>
<!-- <link rel="stylesheet" href="/css/style.css"/>-->
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<button class="navbar-toggler" type="button"
data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<a class="nav-link">Стриминговый сервис</a>
<a class="nav-link" href="/song" th:classappend="${#strings.equals(activeLink, '/song')} ? 'active' : ''">Песни</a>
<a class="nav-link" href="/album" th:classappend="${#strings.equals(activeLink, '/album')} ? 'active' : ''">Альбомы</a>
<a class="nav-link" href="/artist" th:classappend="${#strings.equals(activeLink, '/artist')} ? 'active' : ''">Исполнители</a>
<a class="nav-link" href="/search" th:classappend="${#strings.equals(activeLink, '/search')} ? 'active' : ''">Поиск</a>
</ul>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="container container-padding" layout:fragment="content">
</div>
</div>
</body>
<th:block layout:fragment="scripts">
</th:block>
</html>

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div><span th:text="${error}"></span></div>
<a href="/">На главную</a>
</div>
</body>
</html>

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
<div>It's works!</div>
<a href="123">ERROR</a>
</div>
</body>
</html>

View File

@@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<body>
<div layout:fragment="content">
<form action="#" th:action="@{/search}" method="get">
<div class="search-box">
<label for="name"><h2>Введите имя для поиска:</h2></label>
<input type="text" class="form-control" id="name" th:name="name" th:value="${name}" required>
<br>
<div>
<button type="submit" class="btn btn-primary" >Поиск</button>
</div>
</div>
<br>
<div>
<h2>Результат поиска "<span th:text="${name}"></span>"</h2>
<div th:if="searchResult">
<h3>Песни</h3>
<ul>
<li th:each="song : ${songs}">
<span th:text="${song.songName}"></span>
</li>
</ul>
<h3>Альбомы</h3>
<ul>
<li th:each="album : ${albums}">
<span th:text="${album.albumName}"></span>
</li>
</ul>
<h3>Исполнители</h3>
<ul>
<li th:each="artist : ${artists}">
<span th:text="${artist.artistName}"></span>
</li>
</ul>
</div>
</div>
</form>
</div>
</body>

View File

@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div th:text="${errors}" class="margin-bottom alert-danger"></div>
<form action="#" th:action="@{/song/{id}(id=${id})}" th:object="${songDTO}" method="post">
<div class="mb-3">
<label for="songName" class="form-label">Название</label>
<input type="text" class="form-control" id="songName" th:field="${songDTO.songName}" required>
<label for="duration" class="form-label">Продолжительность</label>
<input type="number" step="0.1" class="form-control" id="duration" th:field="${songDTO.duration}" required>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary button-fixed">
<span th:if="${songId == null}">Добавить</span>
<span th:if="${songId != null}">Обновить</span>
</button>
<a class="btn btn-secondary button-fixed" th:href="@{/song}">
Назад
</a>
</div>
</form>
</div>
</body>
</html>

View File

@@ -0,0 +1,54 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<h1 class="text-center mb-4">Песни</h1>
<div>
<a class="btn btn-success button-fixed"
th:href="@{/song/edit}">
<i class="fa-solid fa-plus"></i> Добавить
</a>
</div>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col">Продолжительность</th>
<th scope="col">Альбом</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr th:each="song, iterator: ${songs}">
<td th:text="${song.songName}"></td>
<td th:text="${song.duration}"></td>
<td th:text="${song.albumName}"></td>
<td>
<div class="btn-album" role="group" aria-label="Basic example">
<a class="btn btn-warning button-fixed button-sm"
th:href="@{/song/edit/{id}(id=${song.id})}">
<i class="fa fa-pencil" aria-hidden="true"></i> Изменить
</a>
<button type="button" class="btn btn-danger button-fixed button-sm"
th:attr="onclick=|confirm('Удалить запись?') && document.getElementById('remove-${song.id}').click()|">
<i class="fa fa-trash" aria-hidden="true"></i> Удалить
</button>
</div>
<form th:action="@{/song/delete/{id}(id=${song.id})}" method="post">
<button th:id="'remove-' + ${song.id}" type="submit" style="display: none">
Удалить
</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Имя</th>
<th scope="col">Жанр</th>
</tr>
</thead>
<tbody>
<tr th:each="artist, iterator: ${artists}">
<td th:text="${artist.artistName}"></td>
<td th:text="${artist.genre}"></td>
</tr>
</tbody>
<a class="btn btn-secondary button-fixed" th:href="@{/album}">
Назад
</a>
</table>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,36 @@
<!DOCTYPE html>
<html lang="en"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{default}" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div layout:fragment="content">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th scope="col">Название</th>
<th scope="col">Продолжительность</th>
<th></th>
</tr>
</thead>
<tbody>
<tr th:each="song, iterator: ${songs}">
<td th:text="${song.songName}"></td>
<td th:text="${song.duration}"></td>
<td>
<form method="post" th:action="@{/album/deleteSongFromAlbum/{id}(id=${song.id})}">
<button type="submit" class="btn btn-danger button-fixed button-sm">Удалить</button>
</form>
</td>
</tr>
</tbody>
<a class="btn btn-secondary button-fixed" th:href="@{/album}">
Назад
</a>
</table>
</div>
</div>
</body>
</html>

View File

@@ -1,118 +1,215 @@
package ru.ulstu.is.sbapp;
import jakarta.transaction.Transactional;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.model.Album;
import ru.ulstu.is.sbapp.database.service.ArtistService;
import ru.ulstu.is.sbapp.database.service.FindByNameService;
import ru.ulstu.is.sbapp.database.service.SongService;
import ru.ulstu.is.sbapp.database.service.AlbumService;
import jakarta.persistence.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SpringBootTest
public class SbappApplicationTests {
@Autowired
private AlbumService albumService;
@Autowired
private ArtistService artistService;
@Autowired
private SongService songService;
@Autowired
private ArtistService artistService;
private FindByNameService findService;
@Test
void testSongCreate(){
songService.deleteAllSongs();
final Song song = songService.addSong("Song",2.36);
Assertions.assertNotNull(song.getId());
}
@Test
void test1(){
void testArtistCreate(){
artistService.deleteAllArtists();
final Artist artist = artistService.addArtist("Artist", "genre");
Assertions.assertNotNull(artist.getId());
}
@Test
void testAlbumCreate() throws IOException {
albumService.deleteAllAlbums();
artistService.deleteAllArtists();
songService.deleteAllSongs();
final Artist artist1 = artistService.addArtist("Artist", "genre");
final Artist artist2 = artistService.addArtist("Artist", "genre");
final Album album1= albumService.addAlbum("Album");
final Album album2= albumService.addAlbum("Album");
album1.addArtist(artist1);
album2.addArtist(artist1);
album2.addArtist(artist2);
Assertions.assertNotNull(album1.getId());
Assertions.assertNotNull(album2.getId());
}
final Song song = songService.addSong("song", 2.50);
Assertions.assertNotNull(song.getId());
Song song2 = songService.addSong("song2", 3.10);
List<Song> songs = new ArrayList<>();
songs.add(song);
songs.add(song2);
Artist artist = artistService.addArtist("artist", "genre");
Assertions.assertNotNull(artist.getId());
Artist artist2 = artistService.addArtist("artist2", "genre");
List<Artist> artists = new ArrayList<>();
artists.add(artist);
artists.add(artist2);
Album album = albumService.addAlbum("album");
Album album2 = albumService.addAlbum("album2");
Assertions.assertNotNull(album.getId());
albumService.addArtist(album, artists);
albumService.addSong(album, songs);
artist2 = artistService.updateArtist(artist2.getId(), "artist3", "genre2");
Assertions.assertEquals("artist3", artistService.findArtist(artist2.getId()).getArtistName());
song2 = songService.updateSong(song2.getId(), "song3", 3.40, null);
Assertions.assertEquals("song3", songService.findSong(song2.getId()).getSongName());
album = albumService.updateAlbum(album.getId(), "album3", songs, artists);
Assertions.assertEquals("album3", albumService.findAlbum(album.getId()).getAlbumName());
Assertions.assertEquals(true, artistService.findAllSongsProducedArtist(artist).contains(song));
Assertions.assertEquals(true, songService.findSongsInAlbum(song).contains(song2));
@Test
void ReadAlbum() throws IOException {
albumService.deleteAllAlbums();
artistService.deleteAllArtists();
songService.deleteAllSongs();
final Artist artist1 = artistService.addArtist("Artist", "genre");
final Song song = songService.addSong("Song",3.28);
final Album album2= albumService.addAlbum("Album");
album2.addArtist(artist1);
final Album findAlbum = albumService.findAlbum(album2.getId());
Assertions.assertEquals(album2, findAlbum);
}
@Test
void ReadAlbumTrue() throws IOException {
albumService.deleteAllAlbums();
artistService.deleteAllArtists();
songService.deleteAllSongs();
final Artist artist1 = artistService.addArtist("Artist", "genre");
final Artist artist2 = artistService.addArtist("Artist2", "genre");
final Song song = songService.addSong("Song",3.19);
Album album2= albumService.addAlbum("Album");
album2 =albumService.addArtist(album2.getId(),artist1.getId());
album2 =albumService.addArtist(album2.getId(),artist2.getId());
final Album findAlbum = albumService.findAlbum(album2.getId());
Assertions.assertEquals(album2, findAlbum);
}
@Test
void ReadSong(){
songService.deleteAllSongs();
final Song song = songService.addSong("Song",3.29);
final Album album = albumService.addAlbum("Album");
song.setAlbum(album);
final Song findSong = songService.findSong(song.getId());
Assertions.assertEquals(song, findSong);
}
@Test
void ReadArtist(){
artistService.deleteAllArtists();
final Artist artist = artistService.addArtist("Artist", "genre");
final Artist findArtist = artistService.findArtist(artist.getId());
Assertions.assertEquals(artist, findArtist);
final Album findAlbum = albumService.findAlbum(album.getId());
Assertions.assertEquals(album, findAlbum);
//TestReadAll
final List<Song> songss = songService.findAllSongs();
Assertions.assertEquals(songss.size(), 2);
final List<Artist> artistss = artistService.findAllArtists();
Assertions.assertEquals(artistss.size(), 2);
final List<Album> albumss = albumService.findAllAlbums();
Assertions.assertEquals(albumss.size(), 2);
//TestReadNotFound
//album2 = albumService.updateAlbum(album2.getId(), "стул",songs, artistService.findAllArtists());
//albumService.deleteAlbum(album.getId());
//albumService.deleteAlbum(album2.getId());
List<Song> list = songService.findAllSongs();
List<Artist> list2 = artistService.findAllArtists();
albumService.deleteAllAlbums();
songService.deleteAllSongs();
artistService.deleteAllArtists();
Assertions.assertThrows(EntityNotFoundException.class, () -> songService.findSong(-1L));
Assertions.assertThrows(EntityNotFoundException.class, () -> artistService.findArtist(-1L));
Assertions.assertThrows(EntityNotFoundException.class, () -> albumService.findAlbum(-1L));
//TestReadAllEmpty
final List<Song> newComponents = songService.findAllSongs();
Assertions.assertEquals(newComponents.size(), 0);
final List<Album> newOrders = albumService.findAllAlbums();
Assertions.assertEquals(newOrders.size(), 0);
final List<Artist> newArtists = artistService.findAllArtists();
Assertions.assertEquals(newArtists.size(), 0);
}
}
@Test
void testAlbumCheck() throws IOException {
albumService.deleteAllAlbums();
artistService.deleteAllArtists();
songService.deleteAllSongs();
final Artist artist1 = artistService.addArtist("Artist", "genre");
final Artist artist2 = artistService.addArtist("Artist1", "genre1");
final Song song = songService.addSong("Song",3.28);
final Album album2= albumService.addAlbum("Album");
album2.addArtist(artist1);
album2.addArtist(artist2);
Assertions.assertEquals(album2.getArtists().size(),2);
}
@Test
void testAlbumPreviewCheck() throws IOException {
albumService.deleteAllAlbums();
artistService.deleteAllArtists();
songService.deleteAllSongs();
final Artist artist1 = artistService.addArtist("Artist", "genre");
final Artist artist2 = artistService.addArtist("Artist1", "genre1");
final Song song = songService.addSong("Song",2.10);
final Album album2= albumService.addAlbum("Album");
album2.addArtist(artist1);
album2.addArtist(artist2);
Album v = albumService.findAlbum(album2.getId());
}
@Test
void testSongReadNotFound() {
songService.deleteAllSongs();
Assertions.assertThrows(EntityNotFoundException.class, () -> songService.findSong(-1L));
}
@Test
void testArtistReadNotFound() {
artistService.deleteAllArtists();
Assertions.assertThrows(EntityNotFoundException.class, () -> artistService.findArtist(-1L));
}
@Test
void testAlbumReadNotFound() {
albumService.deleteAllAlbums();
Assertions.assertThrows(EntityNotFoundException.class, () -> albumService.findAlbum(-1L));
}
@Test
void testSongCount(){
songService.deleteAllSongs();
final Song song1 = songService.addSong("Song",3.15);
final Song song2 = songService.addSong("Song1",2.43);
final List<Song> songs = songService.findAllSongs();
Assertions.assertEquals(songs.size(),2);
}
@Test
void testArtistCount(){
artistService.deleteAllArtists();
final Artist cat1 = artistService.addArtist("Shorts", "genre");
final Artist ca2 = artistService.addArtist("Comedy", "genre");
final List<Artist> categories = artistService.findAllArtists();
assertEquals(categories.size(),2);
}
@Test
void testAlbumCount() throws IOException {
albumService.deleteAllAlbums();
artistService.deleteAllArtists();
songService.deleteAllSongs();
final Artist cat1 = artistService.addArtist("Artist", "genre");
final Song song2 = songService.addSong("Song",3.17);
final Album album1 = albumService.addAlbum("Album");
final Album album2 = albumService.addAlbum("Album1");
album1.addArtist(cat1);
album2.addArtist(cat1);
final List<Album> albums = albumService.findAllAlbums();
Assertions.assertEquals(albums.size(),2);
}
@Test
void testDop() {
String nameToTest = "a";
// создаем данные для тестирования
albumService.deleteAllAlbums();
artistService.deleteAllArtists();
songService.deleteAllSongs();
final Artist artist1 = artistService.addArtist(nameToTest, "genre");
final Album album1= albumService.addAlbum(nameToTest);
final Song song1 = songService.addSong(nameToTest, 3.29);
album1.addArtist(artist1);
artist1.addAlbum(album1);
album1.addSong(song1);
Map<String, List<Object>> resultMap = findService.GetResult(nameToTest);
List<Object> artistsList = resultMap.get("artists");
assertEquals(1, artistsList.size());
Object artistResult = artistsList.get(0);
assertEquals(nameToTest, ((Artist) artistResult).getArtistName());
List<Object> albumsList = resultMap.get("albums");
assertEquals(1, albumsList.size());
Object albumResult = albumsList.get(0);
assertEquals(nameToTest, ((Album) albumResult).getAlbumName());
List<Object> songsList = resultMap.get("songs");
assertEquals(1, songsList.size());
Object songResult = songsList.get(0);
assertEquals(nameToTest, ((Song) songResult).getSongName());
}
}