Compare commits

...

No commits in common. "main" and "lab03" have entirely different histories.
main ... lab03

26 changed files with 1470 additions and 24 deletions

55
.gitignore vendored
View File

@ -1,26 +1,37 @@
# ---> Java
# Compiled class file
*.class
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
# Log file
*.log
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
# BlueJ files
*.ctxt
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

View File

@ -1,2 +0,0 @@
# PIbd-22_Artamonova_T.V._IP

26
build.gradle Normal file
View File

@ -0,0 +1,26 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.2'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'ru.ulstu.is'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
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'
implementation 'org.hibernate.validator:hibernate-validator'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

240
gradlew vendored Normal file
View File

@ -0,0 +1,240 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

91
gradlew.bat vendored Normal file
View File

@ -0,0 +1,91 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

1
settings.gradle Normal file
View File

@ -0,0 +1 @@
rootProject.name = 'sbapp'

View File

@ -0,0 +1,13 @@
package ru.ulstu.is.sbapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SbappApplication {
public static void main(String[] args) {
SpringApplication.run(SbappApplication.class, args);
}
}

View File

@ -0,0 +1,13 @@
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.WebMvcConfigurer;
@Configuration
class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -0,0 +1,20 @@
package ru.ulstu.is.sbapp.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ru.ulstu.is.sbapp.interfaces.DoubleType;
import ru.ulstu.is.sbapp.interfaces.StringType;
@Configuration
public class TypeConfiguration {
@Bean(value = "str")
public StringType createStrType(){
return new StringType();
}
@Bean(value = "double")
public DoubleType createDoubleType(){
return new DoubleType();
}
}

View File

@ -0,0 +1,43 @@
package ru.ulstu.is.sbapp.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import ru.ulstu.is.sbapp.service.ServiceType;
@RestController
public class MainController {
private final ServiceType Service;
public MainController(ServiceType service) {
Service = service;
}
@GetMapping("/Func1")
public Object Func1(@RequestParam(value = "Type") String Type,
@RequestParam(value = "value1") Object value1,
@RequestParam(value = "value2") Object value2){
return Service.Func1(value1,value2,Type);
}
@GetMapping("/Func2")
public Object Func2(@RequestParam(value = "Type") String Type,
@RequestParam(value = "value1") Object value1,
@RequestParam(value = "value2") Object value2){
return Service.Func2(value1, value2, Type);
}
@GetMapping("/Func3")
public Object Func3(@RequestParam(value = "Type") String Type,
@RequestParam(value = "value1") Object value1,
@RequestParam(value = "value2") Object value2){
return Service.Func3(value1,value2,Type);
}
@GetMapping("/Func4")
public Object Func4(@RequestParam(value = "Type") String Type,
@RequestParam(value = "value1") Object value1,
@RequestParam(value = "value2") Object value2){
return Service.Func4(value1,value2,Type);
}
}

View File

@ -0,0 +1,101 @@
package ru.ulstu.is.sbapp.database.model;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "album")
public class Album {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String albumName;
@OneToMany(mappedBy = "album", cascade = CascadeType.ALL, orphanRemoval = true,fetch = FetchType.LAZY)
private List<Song> songs = new ArrayList<>();
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY)
@JoinTable(name = "albums_artists",
joinColumns = @JoinColumn(name = "album_id"),
inverseJoinColumns = @JoinColumn(name = "artist_id"))
private List<Artist> artists = new ArrayList<>();
public Album(){
}
public Album(String albumName){
this.albumName = albumName;
}
public Long getId() {
return id;
}
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);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Album album = (Album) o;
return Objects.equals(id, album.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Album{" +
"id=" + id +
", albumName='" + albumName + '\'' +
'}';
}
}

View File

@ -0,0 +1,89 @@
package ru.ulstu.is.sbapp.database.model;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
public class Artist {
@Id
@GeneratedValue
private Long id;
@Column(name = "name")
private String artistName;
@Column(name = "genre")
private String genre;
@ManyToMany(mappedBy = "artists", cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
private List<Album> albums;
public Artist() {
}
public Artist(String artistName, String genre) {
this.artistName = artistName;
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> getAlbums() {
return albums;
}
public void setAlbums(List<Album> albums) {
this.albums = albums;
}
public void addAlbum(Album album) {
if (this.albums == null) {
this.albums = new ArrayList<>();
}
if (!this.albums.contains(album))
this.albums.add(album);
}
public void removeAlbum(Album album) {
if (this.albums.contains(album))
this.albums.remove(album);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Artist artist = (Artist) o;
return Objects.equals(id, artist.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Artist{" +
"id=" + id +
", artistName='" + artistName + '\'' +
", genre='" + genre + '\'' +
'}';
}
}

View File

@ -0,0 +1,69 @@
package ru.ulstu.is.sbapp.database.model;
import jakarta.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "song")
public class Song {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String songName;
@Column(name = "duration")
private Double duration;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "album_id")
private Album album;
public Song(){
}
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 void setSongDuration(Double duration) {
this.duration = duration;
}
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);
}
@Override
public String toString() {
return "Song{" +
"id=" + id +
", songName='" + songName + '\'' +
", duration='" + duration + '\'' +
'}';
}
}

View File

@ -0,0 +1,143 @@
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.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.Collections;
import java.util.List;
@Service
public class AlbumService {
@PersistenceContext
private EntityManager em;
@Transactional
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;
}
@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(Long AlbumId, Long ArtistId){
final Album album = em.find(Album.class, AlbumId);
if (album == null) {
throw new EntityNotFoundException(String.format("Album with id [%s] is not found", AlbumId));
}
final Artist artist = em.find(Artist.class, ArtistId);
if (artist == null) {
throw new EntityNotFoundException(String.format("Artist with id [%s] is not found", ArtistId));
}
album.addArtist(artist);
return em.merge(album);
}
@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 List<Album> findAllAlbums() {
return em.createQuery("select s from Album s", Album.class)
.getResultList();
}
@Transactional
public Album updateAlbum(Long id, String name, List<Song> newSongs, List<Artist> newArtists) {
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;
}
@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;
}
@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();
}
@Transactional
public List<Album> findFilteredAlbum(Long[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("Array id is empty");
}
List<Album> albumList = new ArrayList<>();
for (Long aLong : arr) {
albumList.add(em.find(Album.class, aLong));
}
return albumList;
}
}

View File

@ -0,0 +1,97 @@
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.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.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ArtistService {
@PersistenceContext
private EntityManager em;
private SongService ss;
@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");
}
final Artist artist = new Artist(name, genre);
em.persist(artist);
return 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 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;
}
@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");
}
final Artist currentArtist = findArtist(id);
currentArtist.setArtistName(name);
currentArtist.setGenre(genre);
em.merge(currentArtist);
return currentArtist;
}
@Transactional
public Artist deleteArtist(Long id) {
final Artist currentArtist = findArtist(id);
int size = currentArtist.getAlbums().size();
for (int i = 0; i < size; i++) {
Album temp = currentArtist.getAlbums().get(i);
temp.removeArtist(currentArtist);
currentArtist.removeAlbum(temp);
em.remove(temp);
}
em.remove(currentArtist);
return currentArtist;
}
@Transactional
public List<Song> findAllSongsProducedArtist(Artist currentArtist){
if(currentArtist.getAlbums().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();
}
}

View File

@ -0,0 +1,48 @@
package ru.ulstu.is.sbapp.database.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
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.*;
@Service
public class FindByNameService {
@PersistenceContext
private EntityManager em;
@Transactional
public Map<String, List<Object>> GetResult(String name) {
Map<String, List<Object>> resultMap = new HashMap<>();
// запрос для поиска песен по названию
List<Song> songs = em.createQuery("SELECT s FROM Song s WHERE s.songName = :name", Song.class)
.setParameter("name", name).getResultList();
// запрос для поиска альбомов по названию
List<Album> albums = em.createQuery("SELECT a FROM Album a WHERE a.albumName = :name", Album.class)
.setParameter("name", name).getResultList();
// запрос для поиска артистов по имени
List<Artist> artists = em.createQuery("SELECT a FROM Artist a WHERE a.artistName = :name", Artist.class)
.setParameter("name", name).getResultList();
// добавляем результаты поиска песен в resultMap
List<Object> songsResult = new ArrayList<>(songs);
resultMap.put("songs", songsResult);
// добавляем результаты поиска альбомов в resultMap
List<Object> albumsResult = new ArrayList<>(albums);
resultMap.put("albums", albumsResult);
// добавляем результаты поиска артистов в resultMap
List<Object> artistsResult = new ArrayList<>(artists);
resultMap.put("artists", artistsResult);
return resultMap;
}
}

View File

@ -0,0 +1,91 @@
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.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.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class SongService {
@PersistenceContext
private EntityManager em;
@Transactional
public Song addSong(String songName, Double duration) {
if (!StringUtils.hasText(songName) || duration <= 0) {
throw new IllegalArgumentException("Song name is null or empty");
}
final Song song = new Song(songName, duration);
em.persist(song);
return song;
}
@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;
}
@Transactional(readOnly = true)
public List<Song> findAllSongs() {
return em.createQuery("select s from Song s", Song.class)
.getResultList();
}
@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");
}
final Song currentSong = findSong(id);
currentSong.setSongName(songName);
currentSong.setSongDuration(duration);
currentSong.setAlbum(album);
em.merge(currentSong);
return currentSong;
}
@Transactional
public Song deleteSong(Long id) {
final Song currentSong= findSong(id);
if(currentSong.getAlbum() != null) currentSong.getAlbum().removeSong(currentSong);
em.remove(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();
}
@Transactional
public void deleteAllSongs() {
em.createQuery("delete from Song").executeUpdate();
}
}

View File

@ -0,0 +1,23 @@
package ru.ulstu.is.sbapp.interfaces;
public class DoubleType implements ITypeOfData<Double> {
@Override
public Double Func1(Double value1, Double value2) {
return value1 + value2;
}
@Override
public Double Func2(Double value1, Double value2) {
return Math.min(value1, value2);
}
@Override
public Double Func3(Double value1, Double value2) {
return Math.max(value1, value2);
}
@Override
public Double Func4(Double value1, Double value2) {
return Math.pow(value1,value2);
}
}

View File

@ -0,0 +1,8 @@
package ru.ulstu.is.sbapp.interfaces;
public interface ITypeOfData <T>{
T Func1(T value1, T value2);
T Func2(T value1, T value2);
T Func3(T value1, T value2);
T Func4(T value1, T value2);
}

View File

@ -0,0 +1,26 @@
package ru.ulstu.is.sbapp.interfaces;
import java.util.Locale;
public class StringType implements ITypeOfData<String> {
@Override
public String Func1(String value1, String value2) {
return value1 + value2;
}
@Override
public String Func2(String value1, String value2) {
return value1.toUpperCase() + value2.toUpperCase();
}
@Override
public String Func3(String value1, String value2) {
String[] array = value1.split(value2);
return String.join(" ", array);
}
@Override
public String Func4(String value1, String value2) {
return value1.toLowerCase() + value2.toLowerCase();
}
}

View File

@ -0,0 +1,58 @@
package ru.ulstu.is.sbapp.service;
import org.springframework.stereotype.Service;
import org.springframework.context.ApplicationContext;
import ru.ulstu.is.sbapp.interfaces.ITypeOfData;
@Service
public class ServiceType {
private final ApplicationContext applicationContext;
private ITypeOfData _type;
private Object _value1;
private Object _value2;
public ServiceType(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
private void ValidateParams(Object value1, Object value2, String type){
_type = (ITypeOfData)applicationContext.getBean(type);
switch (type) {
case "double" -> {
try {
_value1 = Double.valueOf(value1.toString());
_value2 = Double.valueOf(value2.toString());
}catch (Exception ex){
_value1 = 0.0;
_value2 = 0.0;
}
}
case "str" -> {
_value1 = value1;
_value2 = value2;
}
}
}
public Object Func1(Object value1, Object value2, String type){
ValidateParams(value1,value2,type);
return String.format("%s", _type.Func1(_value1,_value2));
}
public Object Func2(Object value1, Object value2, String type){
ValidateParams(value1,value2,type);
return String.format("%s", _type.Func2(_value1, _value2));
}
public Object Func3(Object value1, Object value2, String type){
ValidateParams(value1,value2,type);
return String.format("%s", _type.Func3(_value1,_value2));
}
public Object Func4(Object value1, Object value2, String type){
ValidateParams(value1,value2,type);
return String.format("%s", _type.Func4(_value1,_value2));
}
}

View File

@ -0,0 +1,11 @@
spring.main.banner-mode=off
#server.port=8080
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.settings.trace=false
spring.h2.console.settings.web-allow-others=false

View File

@ -0,0 +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 FindByNameService findService;
@Test
void testSongCreate(){
songService.deleteAllSongs();
final Song song = songService.addSong("Song",2.36);
Assertions.assertNotNull(song.getId());
}
@Test
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());
}
@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);
}
@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());
}
}

View File

@ -0,0 +1,6 @@
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop