12 Commits

Author SHA1 Message Date
nezui1
0cb9fd8de5 с отчетом1 2025-11-15 01:08:59 +04:00
nezui1
0738464e7d с отчетом 2025-11-15 01:06:03 +04:00
maxim
2c210e6657 третья лаба 2025-11-14 20:46:33 +04:00
maxim
c7dc979193 слава богу она сделалась 2025-11-12 18:29:47 +04:00
maxim
17014bcb67 первая лаба 2025-09-19 18:00:01 +04:00
maxim
4a409b63d7 первая лаба(2) 2025-09-05 22:29:19 +04:00
nezui1
12007bd3ea первая лаба 2025-09-05 21:46:02 +04:00
maxim
743b7c1c6a отчет 2025-05-28 22:01:52 +04:00
maxim
499b51d2e1 лаба + отчет 2025-05-28 20:58:31 +04:00
maxim
51875bcc5e лаба + отчет 2025-05-28 20:22:51 +04:00
maxim
51545137be лаба + отчет 2025-05-28 19:45:47 +04:00
maxim
0dd5c03d7d вторая лаба + отчет 2025-05-28 19:30:55 +04:00
227 changed files with 32750 additions and 316 deletions

14
.gitignore vendored
View File

@@ -1,14 +0,0 @@
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix

3
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

9
.idea/internetDev.iml generated Normal file
View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

6
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/internetDev.iml" filepath="$PROJECT_DIR$/.idea/internetDev.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

Binary file not shown.

BIN
LabWork3Report.docx Normal file

Binary file not shown.

View File

@@ -1,2 +0,0 @@
# InternetDev

View File

@@ -1,38 +0,0 @@
<!DOCTYPE html>
<html lang="ru">
<link rel="stylesheet" href="styles.css">
<head>
<title>Каталог</title>
</head>
<body>
<h3>Тут разбита музыка на жанры</h3>
<p>Инфа будет +- такая</p>
<div class="list">
<ul class="punk-list">
<li>
<div class="item">
<img class="catalog" src="pankrock.jpg" alt="Панк-Рок" width=200>
<a href="punkrock.html">Панк-Рок</a>
</div>
</li>
<li>
<div class="item">
<img class="catalog" src="psy.png" alt="Психоделический рок" width=200>
<a href="">Психоделика</a>
</div>
</li>
<li>
<div class="item">
<img class="catalog" src="garajnipunk.jpg" alt="Гаражный-панк" width=200>
<a href="">Гражный-панк</a>
</div>
</li>
</ul>
</div>
<a href="index.html"> Вернуться назад</a>
</body>
</html>

3
demo/.gitattributes vendored Normal file
View File

@@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary

37
demo/.gitignore vendored Normal file
View File

@@ -0,0 +1,37 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

564
demo/ANSWERS.md Normal file
View File

@@ -0,0 +1,564 @@
# Ответы на вопросы по персистентности, ORM, JPA и Hibernate
## 1. Что такое персистентность?
**Персистентность** — это способность данных сохраняться после завершения работы приложения. В нашем проекте данные сохраняются в файле базы данных H2.
**Пример из проекта:**
- Файл `demo/src/main/resources/application.properties`, строки 6-11:
```properties
spring.datasource.url=jdbc:h2:file:./data
spring.jpa.hibernate.ddl-auto=update
```
Настройка `ddl-auto=update` позволяет сохранять данные между перезапусками приложения в файл `./data.mv.db`.
---
## 2. Каким образом можно добавить поддержку персистентности в приложение?
В нашем проекте персистентность добавлена через:
1. **Spring Data JPA** — зависимость в `build.gradle`
2. **H2 Database** — встроенная БД
3. **JPA аннотации** на сущностях
**Пример из проекта:**
- `demo/build.gradle`, строки 30-31:
```gradle
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation "com.h2database:h2:${h2Version}"
```
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 9-10:
```java
@Entity
@Table(name = "artists")
```
---
## 3. Что такое сущность и атрибут сущности?
**Сущность** — это объект предметной области, который имеет идентичность и может быть сохранен в БД. **Атрибут** — это свойство сущности.
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`:
- **Сущность**: `ArtistEntity` (строка 11)
- **Атрибуты**: `name` (строка 13), `description` (строка 15), `epoch` (строка 20), `country` (строка 24)
---
## 4. Как сущности и их атрибуты представлены в реляционной модели данных?
В реляционной модели:
- **Сущность** → **Таблица**
- **Атрибут** → **Колонка**
- **Связь** → **Внешний ключ (Foreign Key)**
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 9-24:
```java
@Entity
@Table(name = "artists") // Таблица "artists"
public class ArtistEntity extends BaseEntity {
@Column(nullable = false) // Колонка "name"
private String name;
@Column(columnDefinition = "text") // Колонка "description"
private String description;
@JoinColumn(name = "epoch_id", nullable = false) // Внешний ключ "epoch_id"
@ManyToOne
private EpochEntity epoch;
}
```
---
## 5. Как сущности и их атрибуты представлены в ООП?
В ООП:
- **Сущность** → **Класс**
- **Атрибут** → **Поле класса**
- **Связь** → **Ссылка на другой объект**
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 11-24:
```java
public class ArtistEntity extends BaseEntity { // Класс (сущность)
private String name; // Поле (атрибут)
private String description; // Поле (атрибут)
private EpochEntity epoch; // Ссылка на другой объект (связь)
private CountryEntity country; // Ссылка на другой объект (связь)
}
```
---
## 6. Как соотносятся понятия ООП и реляционной модели данных?
**ORM (Object-Relational Mapping)** преобразует:
- Класс ↔ Таблица
- Поле ↔ Колонка
- Объект ↔ Строка таблицы
- Ссылка ↔ Внешний ключ
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`:
- Класс `ArtistEntity` → таблица `artists` (строка 10)
- Поле `name` → колонка `name` (строка 12-13)
- Поле `epoch` → внешний ключ `epoch_id` (строка 18-20)
---
## 7. Что такое ORM?
**ORM (Object-Relational Mapping)** — технология, которая автоматически преобразует объекты в записи БД и обратно.
**Пример из проекта:**
- Используется через Spring Data JPA и Hibernate
- `demo/src/main/java/com/example/demo/repository/ArtistRepository.java`, строка 12:
```java
public interface ArtistRepository extends JpaRepository<ArtistEntity, Long>
```
JpaRepository автоматически реализует методы для работы с БД через ORM.
---
## 8. Когда следует использовать ORM?
ORM следует использовать когда:
- Приложение использует ООП
- Нужна быстрая разработка
- Бизнес-логика сложная
- Нужна переносимость между БД
**Пример из проекта:**
- Проект использует Spring Boot с JPA для быстрой разработки
- `demo/src/main/resources/application.properties`, строка 10:
```properties
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
```
Можно легко сменить БД, изменив только настройки.
---
## 9. Когда НЕ следует использовать ORM?
ORM НЕ следует использовать когда:
- Критична производительность (высоконагруженные системы)
- Нужны сложные SQL-запросы
- Работа с большими объемами данных (batch-обработка)
- Уже есть оптимизированные SQL-запросы
**Пример из проекта:**
- Для статистики используются JPQL запросы, но для очень сложных запросов может понадобиться нативный SQL
- `demo/src/main/java/com/example/demo/repository/ArtistRepository.java`, строки 19-23:
```java
@Query("select count(a) as totalArtists, ...")
ArtistStatsProjection getArtistsStatistics();
```
---
## 10. Что такое ассоциации в ООП?
**Ассоциация** — это связь между классами, когда один объект ссылается на другой.
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 18-24:
```java
@ManyToOne
private EpochEntity epoch; // Ассоциация с EpochEntity
@ManyToOne
private CountryEntity country; // Ассоциация с CountryEntity
```
---
## 11. Перечислите свойства ассоциаций в ООП.
Свойства ассоциаций:
- **Кратность** (1:1, 1:N, N:M)
- **Направленность** (однонаправленная/двунаправленная)
- **Обязательность** (обязательная/опциональная)
- **Каскадность** (cascade)
**Пример из проекта:**
- **Кратность**: `@ManyToOne` (строка 19) — многие артисты к одной эпохе
- **Направленность**: Двунаправленная связь (ArtistEntity ↔ EpochEntity)
- **Обязательность**: `nullable = false` (строка 18) — обязательная связь
- **Каскадность**: Не используется (по умолчанию нет каскада)
---
## 12. Какими двумя способами можно представить связи между сущностями в реляционной БД?
1. **Внешний ключ (Foreign Key)** — в таблице "многих"
2. **Связующая таблица (Join Table)** — для связи многие-ко-многим
**Пример из проекта:**
- Используется внешний ключ:
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 18-20:
```java
@JoinColumn(name = "epoch_id", nullable = false) // Внешний ключ в таблице artists
@ManyToOne
private EpochEntity epoch;
```
---
## 13. Что такое JPA?
**JPA (Java Persistence API)** — стандарт Java для работы с персистентностью, часть спецификации Jakarta EE.
**Пример из проекта:**
- Используются JPA аннотации из пакета `jakarta.persistence`:
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 3-6:
```java
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
```
---
## 14. Что такое Hibernate?
**Hibernate** — реализация JPA, ORM-фреймворк для Java.
**Пример из проекта:**
- Hibernate используется через Spring Boot:
- `demo/src/main/resources/application.properties`, строка 10:
```properties
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
```
---
## 15. Чем JPA отличается от Hibernate?
- **JPA** — это спецификация (стандарт)
- **Hibernate** — это реализация JPA
**Пример из проекта:**
- Используются JPA аннотации (`@Entity`, `@Column`), но работает через Hibernate
- `demo/src/main/java/com/example/demo/entity/BaseEntity.java`, строки 11-13:
```java
@Id // JPA аннотация
@GeneratedValue(strategy = GenerationType.SEQUENCE) // JPA
@SequenceGenerator(name = "hibernate_sequence") // Hibernate
```
---
## 16. Что такое Spring Data?
**Spring Data** — проект Spring для упрощения работы с данными, предоставляет репозитории.
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/repository/ArtistRepository.java`, строка 12:
```java
public interface ArtistRepository extends JpaRepository<ArtistEntity, Long>
```
`JpaRepository` — часть Spring Data JPA, автоматически реализует CRUD операции.
---
## 17. Что такое соглашение по умолчанию (convention over configuration)?
**Convention over Configuration** — принцип, когда фреймворк использует разумные значения по умолчанию, уменьшая необходимость в конфигурации.
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/repository/ArtistRepository.java`, строки 13-17:
```java
List<ArtistEntity> findByEpochId(Long epochId);
```
Spring Data автоматически создает SQL-запрос по имени метода, не нужно писать реализацию.
---
## 18. Для чего используется аннотация @Entity?
`@Entity` помечает класс как JPA сущность, которая будет отображаться в таблицу БД.
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строка 9:
```java
@Entity
@Table(name = "artists")
public class ArtistEntity extends BaseEntity {
```
---
## 19. Для чего используется аннотация @SecondaryTable?
`@SecondaryTable` используется для отображения сущности на несколько таблиц (в нашем проекте не используется).
---
## 20. Для чего используются аннотации @Embeddable и @Embedded?
`@Embeddable` и `@Embedded` используются для встраивания одного объекта в другой без отдельной таблицы (в нашем проекте не используется).
---
## 21. Для чего используются аннотации @Id и @GeneratedValue?
`@Id` помечает поле как первичный ключ, `@GeneratedValue` указывает стратегию генерации ID.
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/entity/BaseEntity.java`, строки 11-13:
```java
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "hibernate_sequence")
protected Long id;
```
---
## 22. Для чего используются аннотации @Embeddable и @EmbeddedId?
Используются для составных первичных ключей через встраиваемый класс (в нашем проекте не используется).
---
## 23. Для чего используется аннотация @IdClass?
`@IdClass` используется для составных первичных ключей через отдельный класс (в нашем проекте не используется).
---
## 24. В чем разница между @EmbeddedId и @IdClass?
- `@EmbeddedId` — составной ключ как встроенный объект
- `@IdClass` — составной ключ как отдельный класс
В нашем проекте используется простой `@Id` (Long), составные ключи не используются.
---
## 25. Для чего используются аннотации @Basic и @Column?
`@Basic` указывает базовое отображение поля, `@Column` настраивает колонку в таблице.
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 12-16:
```java
@Column(nullable = false) // Колонка не может быть null
private String name;
@Column(columnDefinition = "text") // Тип колонки - text
private String description;
```
---
## 26. Для чего используются аннотации @Lob, @Basic, @Column, @Temporal и @Transient?
- `@Lob` — для больших объектов (BLOB/CLOB)
- `@Basic` — базовое отображение
- `@Column` — настройка колонки
- `@Temporal` — для дат/времени
- `@Transient` — поле не сохраняется в БД
**Пример из проекта:**
- `@Column` используется в `ArtistEntity.java`, строка 15:
```java
@Column(columnDefinition = "text") // Текстовое поле
private String description;
```
---
## 27. Для чего используется аннотация @Enumerated?
`@Enumerated` используется для сохранения enum в БД (в нашем проекте не используется).
---
## 28. Для чего используется аннотация @Access?
`@Access` определяет способ доступа к полям (FIELD или PROPERTY) (в нашем проекте используется FIELD по умолчанию).
---
## 29. Какие аннотации используются для отображения разных типов связей?
- `@OneToOne` — один к одному
- `@OneToMany` — один ко многим
- `@ManyToOne` — многие к одному
- `@ManyToMany` — многие ко многим
**Примеры из проекта:**
- `@ManyToOne`: `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строка 19:
```java
@ManyToOne
private EpochEntity epoch;
```
- `@OneToMany`: `demo/src/main/java/com/example/demo/entity/EpochEntity.java`, строка 18:
```java
@OneToMany(mappedBy = "epoch")
private Set<ArtistEntity> artists = new HashSet<>();
```
---
## 30. Приведите пример реализации однонаправленной one to one связи.
В нашем проекте нет one-to-one связи. Пример был бы:
```java
@Entity
public class ArtistEntity {
@OneToOne
@JoinColumn(name = "profile_id")
private ProfileEntity profile;
}
```
---
## 31. Приведите пример реализации однонаправленной one to many связи.
В нашем проекте все связи двунаправленные. Пример однонаправленной:
```java
@Entity
public class EpochEntity {
@OneToMany
@JoinColumn(name = "epoch_id")
private List<ArtistEntity> artists;
}
```
---
## 32. Приведите пример реализации двунаправленной one to many связи.
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/entity/EpochEntity.java`, строки 18-20:
```java
@OneToMany(mappedBy = "epoch")
@OrderBy("id ASC")
private Set<ArtistEntity> artists = new HashSet<>();
```
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строки 18-20:
```java
@JoinColumn(name = "epoch_id", nullable = false)
@ManyToOne
private EpochEntity epoch;
```
Связь двунаправленная: `EpochEntity` имеет коллекцию `artists`, а `ArtistEntity` имеет ссылку `epoch`.
---
## 33. Приведите пример реализации двунаправленной many to many связи.
В нашем проекте нет many-to-many связи. Пример:
```java
@Entity
public class ArtistEntity {
@ManyToMany
@JoinTable(name = "artist_genre",
joinColumns = @JoinColumn(name = "artist_id"),
inverseJoinColumns = @JoinColumn(name = "genre_id"))
private Set<GenreEntity> genres;
}
```
---
## 34. Какие стратегии выборки данных для связей можно использовать?
- **LAZY** — ленивая загрузка (по умолчанию для `@OneToMany`, `@ManyToMany`)
- **EAGER** — жадная загрузка (по умолчанию для `@OneToOne`, `@ManyToOne`)
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/entity/EpochEntity.java`, строка 18:
```java
@OneToMany(mappedBy = "epoch") // LAZY по умолчанию
private Set<ArtistEntity> artists;
```
- `demo/src/main/java/com/example/demo/entity/ArtistEntity.java`, строка 19:
```java
@ManyToOne // EAGER по умолчанию
private EpochEntity epoch;
```
---
## 35. Чем отличаются стратегии Lazy и Eager?
- **LAZY** — данные загружаются только при обращении (ленивая загрузка)
- **EAGER** — данные загружаются сразу вместе с родительским объектом (жадная загрузка)
**Пример из проекта:**
- При загрузке `ArtistEntity` эпоха загружается сразу (EAGER)
- При загрузке `EpochEntity` артисты загружаются только при обращении к `getArtists()` (LAZY)
---
## 36. Как принимается решение об используемой стратегии выборки данных?
Решение принимается на основе:
- Частоты использования связи
- Производительности
- Размера связанных данных
**Пример из проекта:**
- `@ManyToOne` — EAGER, так как обычно нужна эпоха/страна артиста
- `@OneToMany` — LAZY, так как коллекция может быть большой
---
## 37. Для чего используются аннотации @OrderBy и @OrderColumn?
`@OrderBy` сортирует коллекцию при загрузке, `@OrderColumn` сохраняет порядок в отдельной колонке.
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/entity/EpochEntity.java`, строки 18-20:
```java
@OneToMany(mappedBy = "epoch")
@OrderBy("id ASC") // Сортировка по id при загрузке
private Set<ArtistEntity> artists = new HashSet<>();
```
---
## 38. Когда для работы со связями следует использовать изменение данных в коллекции объекта?
Когда связь управляется владельцем (owner side), изменения в коллекции синхронизируются с БД.
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/entity/EpochEntity.java`, строки 43-50:
```java
public void addArtist(ArtistEntity artist) {
if (!artists.contains(artist)) {
artists.add(artist); // Изменение коллекции
if (artist.getEpoch() != this) {
artist.setEpoch(this); // Синхронизация обратной связи
}
}
}
```
---
## 39. Когда для работы со связями следует использовать DAO?
DAO (Data Access Object) используется для сложных операций, которые нельзя выразить через методы сущности.
**Пример из проекта:**
- `demo/src/main/java/com/example/demo/repository/ArtistRepository.java`, строки 19-23:
```java
@Query("select count(a) as totalArtists, ...")
ArtistStatsProjection getArtistsStatistics();
```
Сложные запросы со статистикой выполняются через репозиторий (аналог DAO), а не через методы сущности.

209
demo/HOW_TO_RUN.md Normal file
View File

@@ -0,0 +1,209 @@
# Инструкция по запуску приложения
## Требования
- **Java 21** (JDK 21)
- **Gradle** (обычно входит в проект через Gradle Wrapper)
Проверьте версию Java:
```bash
java -version
```
Должно быть что-то вроде:
```
openjdk version "21.x.x"
```
## Способы запуска
### 1. Через Gradle Wrapper (рекомендуется)
#### Windows:
```bash
cd demo
.\gradlew.bat bootRun
```
#### Linux/Mac:
```bash
cd demo
./gradlew bootRun
```
### 2. Через IDE (IntelliJ IDEA / Eclipse)
1. Откройте проект в IDE
2. Найдите класс `DemoApplication.java` в пакете `com.example.demo`
3. Правой кнопкой мыши → `Run 'DemoApplication'`
### 3. Сборка и запуск JAR файла
#### Сборка:
```bash
cd demo
.\gradlew.bat bootJar # Windows
# или
./gradlew bootJar # Linux/Mac
```
#### Запуск:
```bash
java -jar build/libs/demo-0.0.1-SNAPSHOT.jar
```
## Что происходит при запуске
1. **Создается база данных H2** в файле `./data.mv.db` (в папке `demo`)
2. **Автоматически создаются таблицы** (благодаря `ddl-auto=create`):
- `epochs`
- `countries`
- `artists`
3. **Автоматически создаются начальные данные** (если база пустая):
- **Страны**: Россия, США, Великобритания, Германия, Франция, Япония
- **Эпохи**: 1970-е, 1980-е, 1990-е, 2000-е, 2010-е, 2020-е
4. **Приложение запускается** на порту **8080**
> **Примечание**: Начальные данные создаются только если база данных пустая. При последующих запусках данные сохраняются (если не удалить файл `data.mv.db`).
## Проверка работы
### 1. Проверка через браузер
Откройте в браузере:
- **Swagger UI**: http://localhost:8080/swagger-ui.html
- **API Docs**: http://localhost:8080/api-docs
### 2. Проверка через H2 Console
1. Откройте в браузере: http://localhost:8080/h2-console
2. Настройки подключения:
- **JDBC URL**: `jdbc:h2:file:./data`
- **User Name**: `sa`
- **Password**: `sa`
3. Нажмите "Connect"
4. Выполните SQL запрос:
```sql
SELECT * FROM artists;
SELECT * FROM epochs;
SELECT * FROM countries;
```
### 3. Проверка через API
Используйте Swagger UI или любой HTTP клиент (Postman, curl):
#### Примеры запросов:
**Создать эпоху:**
```bash
curl -X POST http://localhost:8080/api/epochs \
-H "Content-Type: application/json" \
-d '{"name": "1980-е"}'
```
**Создать страну:**
```bash
curl -X POST http://localhost:8080/api/countries \
-H "Content-Type: application/json" \
-d '{"name": "Россия"}'
```
**Получить всех артистов:**
```bash
curl http://localhost:8080/api/artists
```
## Запуск тестов
### Через Gradle:
```bash
cd demo
.\gradlew.bat test # Windows
# или
./gradlew test # Linux/Mac
```
### Через IDE:
Правой кнопкой на папке `test` → `Run Tests`
## Структура базы данных
После первого запуска в папке `demo` появится файл:
- `data.mv.db` - файл базы данных H2
**Важно**: При каждом запуске с `ddl-auto=create` таблицы пересоздаются заново, поэтому данные не сохраняются между перезапусками.
Если нужно сохранять данные между запусками, измените в `application.properties`:
```properties
spring.jpa.hibernate.ddl-auto=update
```
## Возможные проблемы
### 1. Порт 8080 занят
**Ошибка**: `Port 8080 is already in use`
**Решение**:
- Измените порт в `application.properties`:
```properties
server.port=8081
```
- Или остановите процесс, использующий порт 8080
### 2. Java версия не подходит
**Ошибка**: `Unsupported class file major version`
**Решение**: Установите Java 21
### 3. База данных не создается
**Решение**:
- Убедитесь, что у приложения есть права на запись в папку `demo`
- Проверьте настройки в `application.properties`
### 4. Ошибки компиляции
**Решение**:
```bash
cd demo
.\gradlew.bat clean build
```
## Полезные команды
### Очистка проекта:
```bash
.\gradlew.bat clean
```
### Пересборка:
```bash
.\gradlew.bat clean build
```
### Просмотр зависимостей:
```bash
.\gradlew.bat dependencies
```
### Запуск с отладкой:
Добавьте в `application.properties`:
```properties
logging.level.com.example.demo=DEBUG
```
## Остановка приложения
- В терминале: `Ctrl + C`
- В IDE: нажмите кнопку "Stop" в панели запуска
## Следующие шаги
1. Откройте Swagger UI: http://localhost:8080/swagger-ui.html
2. Протестируйте API через Swagger
3. Проверьте данные в H2 Console
4. Запустите тесты для проверки функциональности

39
demo/build.gradle Normal file
View File

@@ -0,0 +1,39 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.5'
id 'io.spring.dependency-management' version '1.1.5'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
description = 'Demo project for Spring Boot'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
mavenCentral()
}
ext {
h2Version = "2.4.240"
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation "com.h2database:h2:${h2Version}"
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
tasks.named('test') {
useJUnitPlatform()
}

BIN
demo/data.mv.db Normal file

Binary file not shown.

60
demo/data.trace.db Normal file
View File

@@ -0,0 +1,60 @@
2025-11-14 20:15:51.893939+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "[*]DROPTABLE COUNTRIES"; ожидалось "DELETE, DROP"
Syntax error in SQL statement "[*]DROPTABLE COUNTRIES"; expected "DELETE, DROP"; SQL statement:
DROPTABLE COUNTRIES [42001-240]
2025-11-14 20:16:02.103322+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Невозможно удалить "COUNTRIES", пока существует зависимый объект "FK7SDOJ1330RH52SHDCVIL7SD4J"
Cannot drop "COUNTRIES" because "FK7SDOJ1330RH52SHDCVIL7SD4J" depends on it; SQL statement:
DROP TABLE COUNTRIES [90107-240]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:644)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.command.ddl.DropTable.prepareDrop(DropTable.java:104)
at org.h2.command.ddl.DropTable.update(DropTable.java:129)
at org.h2.command.CommandContainer.update(CommandContainer.java:139)
at org.h2.command.Command.executeUpdate(Command.java:306)
at org.h2.command.Command.executeUpdate(Command.java:250)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:262)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1344)
at org.h2.server.web.WebApp.query(WebApp.java:1142)
at org.h2.server.web.WebApp.query(WebApp.java:1118)
at org.h2.server.web.WebApp.process(WebApp.java:244)
at org.h2.server.web.WebApp.processRequest(WebApp.java:176)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:175)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:175)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:175)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:175)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:150)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1736)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:63)
at java.base/java.lang.Thread.run(Thread.java:1583)

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

Binary file not shown.

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
demo/gradlew vendored Normal file
View File

@@ -0,0 +1,251 @@
#!/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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# 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/HEAD/platforms/jvm/plugins-application/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
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# 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="\\\"\\\""
# 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
if ! command -v java >/dev/null 2>&1
then
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
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
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
# 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"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# 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" "$@"

94
demo/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@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
@rem SPDX-License-Identifier: Apache-2.0
@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=.
@rem This is normally unused
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. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
: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
demo/settings.gradle Normal file
View File

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

View File

@@ -0,0 +1,13 @@
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

View File

@@ -0,0 +1,23 @@
package com.example.demo.config;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.Contact;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenApiConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("Punk Rock API")
.version("1.0.0")
.description("REST API для управления данными о панк-рок исполнителях")
.contact(new Contact()
.name("Developer")
.email("developer@example.com")));
}
}

View File

@@ -0,0 +1,10 @@
package com.example.demo.configuration;
public class Constants {
public static final String DEV_ORIGIN = "http://localhost:5173";
public static final String API_URL = "/api";
private Constants() {
}
}

View File

@@ -0,0 +1,20 @@
package com.example.demo.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(@NonNull CorsRegistry registry) {
registry
.addMapping(Constants.API_URL + "/**")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedOrigins("http://localhost:3000", "http://localhost:5173", Constants.DEV_ORIGIN)
.allowedHeaders("*")
.allowCredentials(true);
}
}

View File

@@ -0,0 +1,54 @@
package com.example.demo.controller;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import jakarta.validation.Valid;
import com.example.demo.configuration.Constants;
import com.example.demo.dto.ArtistRq;
import com.example.demo.dto.ArtistRs;
import com.example.demo.service.ArtistService;
@RestController
@RequestMapping(Constants.API_URL + ArtistController.URL)
public class ArtistController {
public static final String URL = "/artists";
private final ArtistService artistService;
public ArtistController(ArtistService artistService) {
this.artistService = artistService;
}
@GetMapping
public List<ArtistRs> getAll() {
return artistService.getAll();
}
@GetMapping("/{id}")
public ArtistRs get(@PathVariable Long id) {
return artistService.get(id);
}
@PostMapping
public ArtistRs create(@RequestBody @Valid ArtistRq dto) {
return artistService.create(dto);
}
@PutMapping("/{id}")
public ArtistRs update(@PathVariable Long id, @RequestBody @Valid ArtistRq dto) {
return artistService.update(id, dto);
}
@DeleteMapping("/{id}")
public ArtistRs delete(@PathVariable Long id) {
return artistService.delete(id);
}
}

View File

@@ -0,0 +1,54 @@
package com.example.demo.controller;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import jakarta.validation.Valid;
import com.example.demo.configuration.Constants;
import com.example.demo.dto.CountryRq;
import com.example.demo.dto.CountryRs;
import com.example.demo.service.CountryService;
@RestController
@RequestMapping(Constants.API_URL + CountryController.URL)
public class CountryController {
public static final String URL = "/countries";
private final CountryService countryService;
public CountryController(CountryService countryService) {
this.countryService = countryService;
}
@GetMapping
public List<CountryRs> getAll() {
return countryService.getAll();
}
@GetMapping("/{id}")
public CountryRs get(@PathVariable Long id) {
return countryService.get(id);
}
@PostMapping
public CountryRs create(@RequestBody @Valid CountryRq dto) {
return countryService.create(dto);
}
@PutMapping("/{id}")
public CountryRs update(@PathVariable Long id, @RequestBody @Valid CountryRq dto) {
return countryService.update(id, dto);
}
@DeleteMapping("/{id}")
public CountryRs delete(@PathVariable Long id) {
return countryService.delete(id);
}
}

View File

@@ -0,0 +1,54 @@
package com.example.demo.controller;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import jakarta.validation.Valid;
import com.example.demo.configuration.Constants;
import com.example.demo.dto.EpochRq;
import com.example.demo.dto.EpochRs;
import com.example.demo.service.EpochService;
@RestController
@RequestMapping(Constants.API_URL + EpochController.URL)
public class EpochController {
public static final String URL = "/epochs";
private final EpochService epochService;
public EpochController(EpochService epochService) {
this.epochService = epochService;
}
@GetMapping
public List<EpochRs> getAll() {
return epochService.getAll();
}
@GetMapping("/{id}")
public EpochRs get(@PathVariable Long id) {
return epochService.get(id);
}
@PostMapping
public EpochRs create(@RequestBody @Valid EpochRq dto) {
return epochService.create(dto);
}
@PutMapping("/{id}")
public EpochRs update(@PathVariable Long id, @RequestBody @Valid EpochRq dto) {
return epochService.update(id, dto);
}
@DeleteMapping("/{id}")
public EpochRs delete(@PathVariable Long id) {
return epochService.delete(id);
}
}

View File

@@ -0,0 +1,59 @@
package com.example.demo.dto;
public class ArtistDto {
private Integer id;
private String name;
private String description;
private Integer epochId;
private Integer countryId;
public ArtistDto() {}
public ArtistDto(Integer id, String name, String description, Integer epochId, Integer countryId) {
this.id = id;
this.name = name;
this.description = description;
this.epochId = epochId;
this.countryId = countryId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getEpochId() {
return epochId;
}
public void setEpochId(Integer epochId) {
this.epochId = epochId;
}
public Integer getCountryId() {
return countryId;
}
public void setCountryId(Integer countryId) {
this.countryId = countryId;
}
}

View File

@@ -0,0 +1,47 @@
package com.example.demo.dto;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class ArtistRq {
@NotBlank
private String name;
private String description;
@NotNull
private Long epochId;
@NotNull
private Long countryId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getEpochId() {
return epochId;
}
public void setEpochId(Long epochId) {
this.epochId = epochId;
}
public Long getCountryId() {
return countryId;
}
public void setCountryId(Long countryId) {
this.countryId = countryId;
}
}

View File

@@ -0,0 +1,50 @@
package com.example.demo.dto;
public class ArtistRs {
private Long id;
private String name;
private String description;
private EpochRs epoch;
private CountryRs country;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public EpochRs getEpoch() {
return epoch;
}
public void setEpoch(EpochRs epoch) {
this.epoch = epoch;
}
public CountryRs getCountry() {
return country;
}
public void setCountry(CountryRs country) {
this.country = country;
}
}

View File

@@ -0,0 +1,29 @@
package com.example.demo.dto;
public class CountryDto {
private Integer id;
private String name;
public CountryDto() {}
public CountryDto(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,17 @@
package com.example.demo.dto;
import jakarta.validation.constraints.NotBlank;
public class CountryRq {
@NotBlank
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,23 @@
package com.example.demo.dto;
public class CountryRs {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,29 @@
package com.example.demo.dto;
public class EpochDto {
private Integer id;
private String name;
public EpochDto() {}
public EpochDto(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,17 @@
package com.example.demo.dto;
import jakarta.validation.constraints.NotBlank;
public class EpochRq {
@NotBlank
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,23 @@
package com.example.demo.dto;
public class EpochRs {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,92 @@
package com.example.demo.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "artists")
public class ArtistEntity extends BaseEntity {
@Column(nullable = false)
private String name;
@Column(columnDefinition = "text")
private String description;
@JoinColumn(name = "epoch_id", nullable = false)
@ManyToOne
private EpochEntity epoch;
@JoinColumn(name = "country_id", nullable = false)
@ManyToOne
private CountryEntity country;
public ArtistEntity() {
super();
}
public ArtistEntity(String name, String description, EpochEntity epoch, CountryEntity country) {
this();
this.name = name;
this.description = description;
setEpoch(epoch);
setCountry(country);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public EpochEntity getEpoch() {
return epoch;
}
public void setEpoch(EpochEntity epoch) {
if (this.epoch == epoch) {
return;
}
if (this.epoch != null) {
EpochEntity oldEpoch = this.epoch;
this.epoch = null;
oldEpoch.removeArtist(this);
}
this.epoch = epoch;
if (epoch != null) {
epoch.addArtist(this);
}
}
public CountryEntity getCountry() {
return country;
}
public void setCountry(CountryEntity country) {
if (this.country == country) {
return;
}
if (this.country != null) {
CountryEntity oldCountry = this.country;
this.country = null;
oldCountry.removeArtist(this);
}
this.country = country;
if (country != null) {
country.addArtist(this);
}
}
}

View File

@@ -0,0 +1,27 @@
package com.example.demo.entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.SequenceGenerator;
@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "hibernate_sequence")
protected Long id;
protected BaseEntity() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@@ -0,0 +1,61 @@
package com.example.demo.entity;
import java.util.HashSet;
import java.util.Set;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
@Entity
@Table(name = "countries")
public class CountryEntity extends BaseEntity {
@Column(nullable = false)
private String name;
@OneToMany(mappedBy = "country")
@OrderBy("id ASC")
private Set<ArtistEntity> artists = new HashSet<>();
public CountryEntity() {
super();
}
public CountryEntity(String name) {
this();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<ArtistEntity> getArtists() {
return artists;
}
public void addArtist(ArtistEntity artist) {
if (!artists.contains(artist)) {
artists.add(artist);
if (artist.getCountry() != this) {
artist.setCountry(this);
}
}
}
public void removeArtist(ArtistEntity artist) {
if (artists.contains(artist)) {
artists.remove(artist);
if (artist.getCountry() == this) {
artist.setCountry(null);
}
}
}
}

View File

@@ -0,0 +1,61 @@
package com.example.demo.entity;
import java.util.HashSet;
import java.util.Set;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
@Entity
@Table(name = "epochs")
public class EpochEntity extends BaseEntity {
@Column(nullable = false)
private String name;
@OneToMany(mappedBy = "epoch")
@OrderBy("id ASC")
private Set<ArtistEntity> artists = new HashSet<>();
public EpochEntity() {
super();
}
public EpochEntity(String name) {
this();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<ArtistEntity> getArtists() {
return artists;
}
public void addArtist(ArtistEntity artist) {
if (!artists.contains(artist)) {
artists.add(artist);
if (artist.getEpoch() != this) {
artist.setEpoch(this);
}
}
}
public void removeArtist(ArtistEntity artist) {
if (artists.contains(artist)) {
artists.remove(artist);
if (artist.getEpoch() == this) {
artist.setEpoch(null);
}
}
}
}

View File

@@ -0,0 +1,8 @@
package com.example.demo.entity.projection;
public interface ArtistStatsProjection {
Long getTotalArtists();
Long getArtistsWithDescription();
Long getArtistsWithoutDescription();
}

View File

@@ -0,0 +1,9 @@
package com.example.demo.entity.projection;
import com.example.demo.entity.CountryEntity;
public interface CountryStatsProjection {
CountryEntity getCountry();
Long getArtistsCount();
}

View File

@@ -0,0 +1,9 @@
package com.example.demo.entity.projection;
import com.example.demo.entity.EpochEntity;
public interface EpochStatsProjection {
EpochEntity getEpoch();
Long getArtistsCount();
}

View File

@@ -0,0 +1,8 @@
package com.example.demo.error;
public class NotFoundException extends RuntimeException {
public <T> NotFoundException(Class<T> entClass, Long id) {
super(String.format("%s with id %s is not found", entClass.getSimpleName(), id));
}
}

View File

@@ -0,0 +1,51 @@
package com.example.demo.mapper;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.stereotype.Component;
import com.example.demo.dto.ArtistRq;
import com.example.demo.dto.ArtistRs;
import com.example.demo.entity.ArtistEntity;
@Component
public class ArtistMapper {
private final EpochMapper epochMapper;
private final CountryMapper countryMapper;
public ArtistMapper(EpochMapper epochMapper, CountryMapper countryMapper) {
this.epochMapper = epochMapper;
this.countryMapper = countryMapper;
}
public ArtistRq toRqDto(String name, String description, Long epochId, Long countryId) {
final ArtistRq dto = new ArtistRq();
dto.setName(name);
dto.setDescription(description);
dto.setEpochId(epochId);
dto.setCountryId(countryId);
return dto;
}
public ArtistRs toRsDto(ArtistEntity entity) {
final ArtistRs dto = new ArtistRs();
dto.setId(entity.getId());
dto.setName(entity.getName());
dto.setDescription(entity.getDescription());
if (entity.getEpoch() != null) {
dto.setEpoch(epochMapper.toRsDto(entity.getEpoch()));
}
if (entity.getCountry() != null) {
dto.setCountry(countryMapper.toRsDto(entity.getCountry()));
}
return dto;
}
public List<ArtistRs> toRsDtoList(Iterable<ArtistEntity> entities) {
return StreamSupport.stream(entities.spliterator(), false)
.map(this::toRsDto)
.toList();
}
}

View File

@@ -0,0 +1,33 @@
package com.example.demo.mapper;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.stereotype.Component;
import com.example.demo.dto.CountryRq;
import com.example.demo.dto.CountryRs;
import com.example.demo.entity.CountryEntity;
@Component
public class CountryMapper {
public CountryRq toRqDto(String name) {
final CountryRq dto = new CountryRq();
dto.setName(name);
return dto;
}
public CountryRs toRsDto(CountryEntity entity) {
final CountryRs dto = new CountryRs();
dto.setId(entity.getId());
dto.setName(entity.getName());
return dto;
}
public List<CountryRs> toRsDtoList(Iterable<CountryEntity> entities) {
return StreamSupport.stream(entities.spliterator(), false)
.map(this::toRsDto)
.toList();
}
}

View File

@@ -0,0 +1,33 @@
package com.example.demo.mapper;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.stereotype.Component;
import com.example.demo.dto.EpochRq;
import com.example.demo.dto.EpochRs;
import com.example.demo.entity.EpochEntity;
@Component
public class EpochMapper {
public EpochRq toRqDto(String name) {
final EpochRq dto = new EpochRq();
dto.setName(name);
return dto;
}
public EpochRs toRsDto(EpochEntity entity) {
final EpochRs dto = new EpochRs();
dto.setId(entity.getId());
dto.setName(entity.getName());
return dto;
}
public List<EpochRs> toRsDtoList(Iterable<EpochEntity> entities) {
return StreamSupport.stream(entities.spliterator(), false)
.map(this::toRsDto)
.toList();
}
}

View File

@@ -0,0 +1,39 @@
package com.example.demo.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.example.demo.entity.ArtistEntity;
import com.example.demo.entity.projection.ArtistStatsProjection;
public interface ArtistRepository extends JpaRepository<ArtistEntity, Long> {
List<ArtistEntity> findByEpochId(Long epochId);
List<ArtistEntity> findByCountryId(Long countryId);
List<ArtistEntity> findByEpochIdAndCountryId(Long epochId, Long countryId);
@Query("select count(a) as totalArtists, " +
"sum(case when a.description is not null and length(a.description) > 0 then 1 else 0 end) as artistsWithDescription, " +
"sum(case when a.description is null or length(a.description) = 0 then 1 else 0 end) as artistsWithoutDescription " +
"from ArtistEntity a")
ArtistStatsProjection getArtistsStatistics();
@Query("select count(a) as totalArtists, " +
"sum(case when a.description is not null and length(a.description) > 0 then 1 else 0 end) as artistsWithDescription, " +
"sum(case when a.description is null or length(a.description) = 0 then 1 else 0 end) as artistsWithoutDescription " +
"from ArtistEntity a " +
"where a.epoch.id = :epochId")
ArtistStatsProjection getArtistsStatisticsByEpoch(@Param("epochId") Long epochId);
@Query("select count(a) as totalArtists, " +
"sum(case when a.description is not null and length(a.description) > 0 then 1 else 0 end) as artistsWithDescription, " +
"sum(case when a.description is null or length(a.description) = 0 then 1 else 0 end) as artistsWithoutDescription " +
"from ArtistEntity a " +
"where a.country.id = :countryId")
ArtistStatsProjection getArtistsStatisticsByCountry(@Param("countryId") Long countryId);
}

View File

@@ -0,0 +1,28 @@
package com.example.demo.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.example.demo.entity.CountryEntity;
import com.example.demo.entity.projection.CountryStatsProjection;
public interface CountryRepository extends JpaRepository<CountryEntity, Long> {
Optional<CountryEntity> findOneByNameIgnoreCase(String name);
@Query("select c as country, count(a) as artistsCount " +
"from CountryEntity c left join c.artists a " +
"group by c " +
"order by c.id")
List<CountryStatsProjection> getAllCountriesStatistics();
@Query("select c as country, count(a) as artistsCount " +
"from CountryEntity c left join c.artists a " +
"where c.id = :countryId " +
"group by c")
CountryStatsProjection getCountryStatistics(@Param("countryId") Long countryId);
}

View File

@@ -0,0 +1,28 @@
package com.example.demo.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.example.demo.entity.EpochEntity;
import com.example.demo.entity.projection.EpochStatsProjection;
public interface EpochRepository extends JpaRepository<EpochEntity, Long> {
Optional<EpochEntity> findOneByNameIgnoreCase(String name);
@Query("select e as epoch, count(a) as artistsCount " +
"from EpochEntity e left join e.artists a " +
"group by e " +
"order by e.id")
List<EpochStatsProjection> getAllEpochsStatistics();
@Query("select e as epoch, count(a) as artistsCount " +
"from EpochEntity e left join e.artists a " +
"where e.id = :epochId " +
"group by e")
EpochStatsProjection getEpochStatistics(@Param("epochId") Long epochId);
}

View File

@@ -0,0 +1,81 @@
package com.example.demo.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.dto.ArtistRq;
import com.example.demo.dto.ArtistRs;
import com.example.demo.entity.ArtistEntity;
import com.example.demo.entity.CountryEntity;
import com.example.demo.entity.EpochEntity;
import com.example.demo.error.NotFoundException;
import com.example.demo.mapper.ArtistMapper;
import com.example.demo.repository.ArtistRepository;
@Service
public class ArtistService {
private final ArtistRepository repository;
private final EpochService epochService;
private final CountryService countryService;
private final ArtistMapper mapper;
public ArtistService(ArtistRepository repository, EpochService epochService,
CountryService countryService, ArtistMapper mapper) {
this.repository = repository;
this.epochService = epochService;
this.countryService = countryService;
this.mapper = mapper;
}
@Transactional(propagation = Propagation.MANDATORY)
public ArtistEntity getEntity(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(ArtistEntity.class, id));
}
@Transactional(readOnly = true)
public List<ArtistRs> getAll() {
return mapper.toRsDtoList(repository.findAll());
}
@Transactional(readOnly = true)
public ArtistRs get(Long id) {
final ArtistEntity entity = getEntity(id);
return mapper.toRsDto(entity);
}
@Transactional
public ArtistRs create(ArtistRq dto) {
final EpochEntity epoch = epochService.getEntity(dto.getEpochId());
final CountryEntity country = countryService.getEntity(dto.getCountryId());
ArtistEntity entity = new ArtistEntity(
dto.getName(),
dto.getDescription(),
epoch,
country);
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
@Transactional
public ArtistRs update(Long id, ArtistRq dto) {
ArtistEntity entity = getEntity(id);
entity.setName(dto.getName());
entity.setDescription(dto.getDescription());
entity.setEpoch(epochService.getEntity(dto.getEpochId()));
entity.setCountry(countryService.getEntity(dto.getCountryId()));
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
@Transactional
public ArtistRs delete(Long id) {
final ArtistEntity entity = getEntity(id);
repository.delete(entity);
return mapper.toRsDto(entity);
}
}

View File

@@ -0,0 +1,65 @@
package com.example.demo.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.dto.CountryRq;
import com.example.demo.dto.CountryRs;
import com.example.demo.entity.CountryEntity;
import com.example.demo.error.NotFoundException;
import com.example.demo.mapper.CountryMapper;
import com.example.demo.repository.CountryRepository;
@Service
public class CountryService {
private final CountryRepository repository;
private final CountryMapper mapper;
public CountryService(CountryRepository repository, CountryMapper mapper) {
this.repository = repository;
this.mapper = mapper;
}
@Transactional(propagation = Propagation.MANDATORY)
public CountryEntity getEntity(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(CountryEntity.class, id));
}
@Transactional(readOnly = true)
public List<CountryRs> getAll() {
return mapper.toRsDtoList(repository.findAll());
}
@Transactional(readOnly = true)
public CountryRs get(Long id) {
final CountryEntity entity = getEntity(id);
return mapper.toRsDto(entity);
}
@Transactional
public CountryRs create(CountryRq dto) {
CountryEntity entity = new CountryEntity(dto.getName());
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
@Transactional
public CountryRs update(Long id, CountryRq dto) {
CountryEntity entity = getEntity(id);
entity.setName(dto.getName());
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
@Transactional
public CountryRs delete(Long id) {
final CountryEntity entity = getEntity(id);
repository.delete(entity);
return mapper.toRsDto(entity);
}
}

View File

@@ -0,0 +1,65 @@
package com.example.demo.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.dto.EpochRq;
import com.example.demo.dto.EpochRs;
import com.example.demo.entity.EpochEntity;
import com.example.demo.error.NotFoundException;
import com.example.demo.mapper.EpochMapper;
import com.example.demo.repository.EpochRepository;
@Service
public class EpochService {
private final EpochRepository repository;
private final EpochMapper mapper;
public EpochService(EpochRepository repository, EpochMapper mapper) {
this.repository = repository;
this.mapper = mapper;
}
@Transactional(propagation = Propagation.MANDATORY)
public EpochEntity getEntity(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(EpochEntity.class, id));
}
@Transactional(readOnly = true)
public List<EpochRs> getAll() {
return mapper.toRsDtoList(repository.findAll());
}
@Transactional(readOnly = true)
public EpochRs get(Long id) {
final EpochEntity entity = getEntity(id);
return mapper.toRsDto(entity);
}
@Transactional
public EpochRs create(EpochRq dto) {
EpochEntity entity = new EpochEntity(dto.getName());
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
@Transactional
public EpochRs update(Long id, EpochRq dto) {
EpochEntity entity = getEntity(id);
entity.setName(dto.getName());
entity = repository.save(entity);
return mapper.toRsDto(entity);
}
@Transactional
public EpochRs delete(Long id) {
final EpochEntity entity = getEntity(id);
repository.delete(entity);
return mapper.toRsDto(entity);
}
}

View File

@@ -0,0 +1,12 @@
spring.application.name=demo
server.port=8080
springdoc.api-docs.path=/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true

View File

@@ -0,0 +1,13 @@
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
}
}

View File

@@ -0,0 +1,114 @@
package com.example.demo.service;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import com.example.demo.dto.ArtistRs;
import com.example.demo.error.NotFoundException;
import com.example.demo.mapper.ArtistMapper;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class ArtistServiceTests {
@Autowired
private ArtistService service;
@Autowired
private EpochService epochService;
@Autowired
private CountryService countryService;
@Autowired
private ArtistMapper mapper;
@Test
@Order(1)
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
}
@Test
@Order(2)
void getAllTest() {
Assertions.assertNotNull(service.getAll());
Assertions.assertTrue(service.getAll().isEmpty());
}
@Test
@Order(3)
void createTest() {
// Создаем необходимые зависимости
final var epochRq1 = new com.example.demo.dto.EpochRq();
epochRq1.setName("1980-е");
final var epoch1 = epochService.create(epochRq1);
final var epochRq2 = new com.example.demo.dto.EpochRq();
epochRq2.setName("1990-е");
final var epoch2 = epochService.create(epochRq2);
final var countryRq1 = new com.example.demo.dto.CountryRq();
countryRq1.setName("Россия");
final var country1 = countryService.create(countryRq1);
final var countryRq2 = new com.example.demo.dto.CountryRq();
countryRq2.setName("США");
final var country2 = countryService.create(countryRq2);
final ArtistRs artist1 = service.create(mapper.toRqDto("Artist 1", "Description 1", epoch1.getId(), country1.getId()));
final ArtistRs artist2 = service.create(mapper.toRqDto("Artist 2", "Description 2", epoch2.getId(), country2.getId()));
final ArtistRs artist3 = service.create(mapper.toRqDto("Artist 3", "Description 3", epoch1.getId(), country1.getId()));
Assertions.assertEquals(3, service.getAll().size());
Assertions.assertNotNull(artist1.getId());
Assertions.assertNotNull(artist2.getId());
Assertions.assertNotNull(artist3.getId());
final ArtistRs cmpEntity = service.get(artist3.getId());
Assertions.assertEquals(artist3.getId(), cmpEntity.getId());
Assertions.assertEquals(artist3.getName(), cmpEntity.getName());
}
@Test
@Order(4)
void updateTest() {
final var allArtists = service.getAll();
Assertions.assertFalse(allArtists.isEmpty());
final ArtistRs entity = allArtists.get(0);
final Long entityId = entity.getId();
final String oldName = entity.getName();
final var epoch = entity.getEpoch();
final var country = entity.getCountry();
final String test = "TEST ARTIST";
final ArtistRs newEntity = service.update(entityId, mapper.toRqDto(test, "New Description", epoch.getId(), country.getId()));
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
final ArtistRs cmpEntity = service.get(entityId);
Assertions.assertEquals(newEntity.getId(), cmpEntity.getId());
Assertions.assertEquals(newEntity.getName(), cmpEntity.getName());
}
@Test
@Order(5)
void deleteTest() {
final var allArtists = service.getAll();
final int initialSize = allArtists.size();
Assertions.assertTrue(initialSize > 0);
final ArtistRs toDelete = allArtists.get(0);
final Long deleteId = toDelete.getId();
service.delete(deleteId);
Assertions.assertEquals(initialSize - 1, service.getAll().size());
Assertions.assertThrows(NotFoundException.class, () -> service.get(deleteId));
}
}

View File

@@ -0,0 +1,90 @@
package com.example.demo.service;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import com.example.demo.dto.CountryRs;
import com.example.demo.error.NotFoundException;
import com.example.demo.mapper.CountryMapper;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class CountryServiceTests {
@Autowired
private CountryService service;
@Autowired
private CountryMapper mapper;
@Test
@Order(1)
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
}
@Test
@Order(2)
void getAllTest() {
Assertions.assertNotNull(service.getAll());
Assertions.assertTrue(service.getAll().isEmpty());
}
@Test
@Order(3)
void createTest() {
final CountryRs country1 = service.create(mapper.toRqDto("Россия"));
final CountryRs country2 = service.create(mapper.toRqDto("США"));
final CountryRs country3 = service.create(mapper.toRqDto("Тайга"));
Assertions.assertEquals(3, service.getAll().size());
Assertions.assertNotNull(country1.getId());
Assertions.assertNotNull(country2.getId());
Assertions.assertNotNull(country3.getId());
final CountryRs cmpEntity = service.get(country3.getId());
Assertions.assertEquals(country3.getId(), cmpEntity.getId());
Assertions.assertEquals(country3.getName(), cmpEntity.getName());
}
@Test
@Order(4)
void updateTest() {
final var allCountries = service.getAll();
Assertions.assertFalse(allCountries.isEmpty());
final CountryRs entity = allCountries.get(0);
final Long entityId = entity.getId();
final String oldName = entity.getName();
final String test = "TEST";
final CountryRs newEntity = service.update(entityId, mapper.toRqDto(test));
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
final CountryRs cmpEntity = service.get(entityId);
Assertions.assertEquals(newEntity.getId(), cmpEntity.getId());
Assertions.assertEquals(newEntity.getName(), cmpEntity.getName());
}
@Test
@Order(5)
void deleteTest() {
final var allCountries = service.getAll();
final int initialSize = allCountries.size();
Assertions.assertTrue(initialSize > 0);
final CountryRs toDelete = allCountries.get(0);
final Long deleteId = toDelete.getId();
service.delete(deleteId);
Assertions.assertEquals(initialSize - 1, service.getAll().size());
Assertions.assertThrows(NotFoundException.class, () -> service.get(deleteId));
}
}

View File

@@ -0,0 +1,91 @@
package com.example.demo.service;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import com.example.demo.dto.EpochRs;
import com.example.demo.error.NotFoundException;
import com.example.demo.mapper.EpochMapper;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
public class EpochServiceTests {
@Autowired
private EpochService service;
@Autowired
private EpochMapper mapper;
@Test
@Order(1)
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
}
@Test
@Order(2)
void getAllTest() {
Assertions.assertNotNull(service.getAll());
Assertions.assertTrue(service.getAll().isEmpty());
}
@Test
@Order(3)
void createTest() {
final EpochRs epoch1 = service.create(mapper.toRqDto("1980-е"));
final EpochRs epoch2 = service.create(mapper.toRqDto("1990-е"));
final EpochRs epoch3 = service.create(mapper.toRqDto("2000-е"));
Assertions.assertEquals(3, service.getAll().size());
Assertions.assertNotNull(epoch1.getId());
Assertions.assertNotNull(epoch2.getId());
Assertions.assertNotNull(epoch3.getId());
final EpochRs cmpEntity = service.get(epoch3.getId());
Assertions.assertEquals(epoch3.getId(), cmpEntity.getId());
Assertions.assertEquals(epoch3.getName(), cmpEntity.getName());
}
@Test
@Order(4)
void updateTest() {
final var allEpochs = service.getAll();
Assertions.assertFalse(allEpochs.isEmpty());
final EpochRs entity = allEpochs.get(0);
final Long entityId = entity.getId();
final String oldName = entity.getName();
final String test = "TEST";
final EpochRs newEntity = service.update(entityId, mapper.toRqDto(test));
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
final EpochRs cmpEntity = service.get(entityId);
Assertions.assertEquals(newEntity.getId(), cmpEntity.getId());
Assertions.assertEquals(newEntity.getName(), cmpEntity.getName());
}
@Test
@Order(5)
void deleteTest() {
final var allEpochs = service.getAll();
final int initialSize = allEpochs.size();
Assertions.assertTrue(initialSize > 0);
final EpochRs toDelete = allEpochs.get(0);
final Long deleteId = toDelete.getId();
service.delete(deleteId);
Assertions.assertEquals(initialSize - 1, service.getAll().size());
Assertions.assertThrows(NotFoundException.class, () -> service.get(deleteId));
}
}

View File

@@ -0,0 +1,2 @@
spring.datasource.url=jdbc:h2:mem:testdb

View File

@@ -1,43 +0,0 @@
<!DOCTYPE html>
<html lang="ru">
<link rel="stylesheet" href="styles.css">
<head>
<title>Гражданская оборона</title>
</head>
<body>
<p>Здесь можно почитать инфу про исполнителя и перейти на песню</p>
<img src = "grob.jpg" alt="Гражданская оборона" width= 500>
<div class="descriptionForSong">
<p>
«Гражданская Оборона» — культовая советская и российская рок-группа, основанная в 1984 году в Омске Егором Летовым.
Коллектив стал одним из самых влиятельных в андеграундной среде, а его творчество оказало огромное влияние
на развитие русского рока. Группа известна своими резкими, часто провокационными текстами, которые затрагивали
темы социального протеста, экзистенциальных переживаний и критики общества.
</p>
<p>
Музыка «Гражданской Обороны» сочетает в себе элементы панк-рока, гаражного рока и лоу-фая.
Несмотря на минималистичный подход к звучанию, группа смогла создать уникальный стиль, который
стал узнаваемым и вдохновил множество последующих исполнителей.
</p>
<p>
Среди самых известных альбомов группы — «Тоталитаризм», «Мышеловка», «Здорово и вечно»,
«Русское поле экспериментов» и «Инструкция по выживанию». Творчество «Гражданской Обороны»
остается актуальным и по сей день, а Егор Летов считается одной из ключевых фигур в истории
русской рок-музыки.
</p>
</div>
<p>
Песни:
<ul>
<li><a href = "grobKaifIliBolshe.html">Кайф или больше</a></li>
<li><a href = "">Зоопарк</a></li>
<li><a href = "">Новая патриотическая</a></li>
</ul>
</p>
<a href="index.html"> Вернуться назад</a>
</body>
</html>

View File

@@ -1,49 +0,0 @@
//grobKaifIliBolshe
<!DOCTYPE html>
<html lang="ru">
<link rel="stylesheet" href="styles.css">
<head>
<title>Гражданская оборона - "Кайф или больше"</title>
</head>
<body>
<h3>Тут будет типа песня</h3>
<img src = "nekrofilia.jpg" alt = "Обложка" width="500" >
<h2>Кайф или больше</h2>
<a href="grob.html">Гражданская оборона</a>
<p>Описание</p>
<ul>
<li>Была выпущена в 1987 году</li>
<li>Входит в альбом некрофилия</li>
</ul>
<div class = "text">
<p>Текст песни:
<br> [Куплет 1]
<br>Рука повисла в небе, полном до краёв
<br>Мои ошибки устилают мой позор
<br>Я сочно благодарен, словно кошкин блёв
<br>И смачно богомолен, словно приговор
<br>[Припев]
<br>Но мне придётся выбирать
<br>Кайф или больше
<br>Рай или больше
<br>Свет или больше… Хей-йо
<br>[Куплет 2]
<br>Я буду ласковым, как тёплый банный лист
<br>Я буду вежливым, как битое окно
<br>Я буду благотворен, словно онанист
<br>Я буду зазеркален, словно всё равно
<br>[Припев]
<br>Но мне придётся выбирать
<br>Кайф или больше
<br>Рай или больше
<br>Свет или больше...хей-йо
</p>
</div>
</body>
<a href="index.html"> Вернуться назад</a>
</html>

View File

@@ -1,28 +0,0 @@
//index
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Панкуха</title>
</head>
<body>
<div class="content">
<h1>Стриминговый сервис <em>"Панкуха"</em></h1>
<img src="res/logo.png" alt="Эмблема" width="200">
<div class="main">
<div class="description">
<p><span style="background-color: blueviolet;">Какие страницы я реализовал:</span></p>
</div>
<ol class = "spisok">
<a href="index.html"><li class="spisok_el">Главная страница</li></a>
<a href="grob.html"><li>Страница исполнителя</li></a>
<li><a href="grobKaifIliBolshe.html">Страница песни</a></li>
<a href="catalog.html"><li>Каталог</li></a>
<a href="punkrock.html"><li>Страница каталога</li></a>
</ol>
</div>
</div>
</body>
</html>

23
punkrock-react/.gitignore vendored Normal file
View File

@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

70
punkrock-react/README.md Normal file
View File

@@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)

18341
punkrock-react/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,46 @@
{
"name": "punkrock-react",
"version": "0.1.0",
"homepage": "/punkrock",
"private": true,
"dependencies": {
"@popperjs/core": "^2.11.8",
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^5.3.6",
"bootstrap-icons": "^1.13.1",
"react": "^18.2.0",
"react-bootstrap-icons": "^1.11.6",
"react-dom": "^18.2.0",
"react-router-dom": "^7.6.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {}
}

View File

@@ -0,0 +1,78 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="src/styles.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
<title>Панкуха</title>
</head>
<body class="bg-dark text-light">
<header class="sticky-top navbar navbar-expand-lg navbar-dark bg-black border-bottom border-punk px-0">
<div class="container-fluid">
<a href="/" class="navbar-brand d-flex align-items-center ms-3">
<img src="/res/logo.png" alt="Панкуха" height="60" class="me-2">
<span class="text-punk fs-4 fw-bold">Панкуха</span>
</a>
<button class="navbar-toggler me-3" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse bg-black" id="navbarContent">
<ul class="navbar-nav w-100 justify-content-end pe-4">
<li class="nav-item dropdown">
<a class="nav-link text-punk fw-bold dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
<i class="bi bi-list me-1"></i>Страницы
</a>
<ul class="dropdown-menu dropdown-menu-end bg-dark">
<li><a class="dropdown-item text-punk" href="/">Главная</a></li>
<li><a class="dropdown-item text-punk" href="/grob">Исполнитель</a></li>
<li><a class="dropdown-item text-punk" href="/grobKaifIliBolshe">Песня</a></li>
<li><a class="dropdown-item text-punk" href="/catalog">Каталог</a></li>
<li><a class="dropdown-item text-punk" href="/punkrock">Список исполнителей</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link text-punk fw-bold" href="https://vk.com/kadyshevever">
<i class="bi bi-people-fill me-1"></i>Контакты
</a>
</li>
</ul>
</div>
</div>
</header>
<main class="container-fluid my-5 flex-grow-1">
<div class="container">
<div class="card bg-dark border-punk mb-4">
<div class="card-body">
<h3 class="text-punk mb-0"><a class="text-punk" href="/punkrock">Панк-Рок</a></h3>
</div>
</div>
<div class="card bg-dark border-punk mb-4">
<div class="card-body">
<h3 class="text-punk mb-0">Психоделика</h3>
</div>
</div>
<div class="card bg-dark border-punk">
<div class="card-body">
<h3 class="text-punk mb-0">Гаражный панк</h3>
</div>
</div>
</div>
</main>
<footer class="bg-black py-3 border-top border-punk mt-auto">
<div class="container">
<div class="d-flex flex-wrap justify-content-between align-items-center">
<p class="mb-0 text-punk">© 2025. Все права защищены.</p>
<nav class="d-flex align-items-center">
<a href="#" class="text-punk me-3">Политика конфиденциальности</a>
</nav>
</div>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@@ -0,0 +1,110 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/styles.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
<title>Панкуха</title>
</head>
<body class="bg-dark text-light">
<header class="sticky-top navbar navbar-expand-lg navbar-dark bg-black border-bottom border-punk px-0">
<div class="container-fluid">
<a href="/" class="navbar-brand d-flex align-items-center ms-3">
<img src="/res/logo.png" alt="Панкуха" height="60" class="me-2">
<span class="text-punk fs-4 fw-bold">Панкуха</span>
</a>
<button class="navbar-toggler me-3" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse bg-black" id="navbarContent">
<ul class="navbar-nav w-100 justify-content-end pe-4">
<li class="nav-item dropdown">
<a class="nav-link text-punk fw-bold dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
<i class="bi bi-list me-1"></i>Страницы
</a>
<ul class="dropdown-menu dropdown-menu-end bg-dark">
<li><a class="dropdown-item text-punk" href="/">Главная</a></li>
<li><a class="dropdown-item text-punk" href="/grob">Исполнитель</a></li>
<li><a class="dropdown-item text-punk" href="/grobKaifIliBolshe">Песня</a></li>
<li><a class="dropdown-item text-punk" href="/catalog">Каталог</a></li>
<li><a class="dropdown-item text-punk" href="/punkrock">Список исполнителей</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link text-punk fw-bold" href="https://vk.com/kadyshevever">
<i class="bi bi-people-fill me-1"></i>Контакты
</a>
</li>
</ul>
</div>
</div>
</header>
<main class="container-fluid my-5 flex-grow-1">
<div class="container">
<div class="card bg-dark border-punk">
<div class="card-body">
<h1 class="text-punk mb-4">Гражданская Оборона</h1>
<div style="text-align: center;">
<img src="/res/grob.jpg" alt="uGrob" class="me-2">
</div>
<p class="lead text-light">
Здесь можно почитать инфу про исполнителя и перейти на песню
</p>
<div class="card bg-dark border-punk mb-4">
<div class="card-body">
<ul class="list-group list-group-flush">
<li class="list-group-item bg-dark text-light border-punk">
«Гражданская Оборона» — культовая советская и российская рок-группа, основанная в 1984 году в Омске Егором Летовым.
Коллектив стал одним из самых влиятельных в андеграундной среде.
</li>
<li class="list-group-item bg-dark text-light border-punk">
Музыка «Гражданской Обороны» сочетает в себе элементы панк-рока, гаражного рока и лоу-фая.
Несмотря на минималистичный подход к звучанию, группа смогла создать уникальный стиль.
</li>
<li class="list-group-item bg-dark text-light border-punk">
Среди самых известных альбомов группы — «Тоталитаризм», «Мышеловка», «Здорово и вечно»,
«Русское поле экспериментов» и «Инструкция по выживанию». Творчество «Гражданской Обороны»
остается актуальным и по сей день, а Егор Летов считается одной из ключевых фигур в истории
русской рок-музыки.
</li>
</ul>
</div>
</div>
<div class="card bg-dark border-punk">
<div class="card-body">
<h3 class="text-punk mb-3">Популярные песни:</h3>
<div class="list-group">
<a class="list-group-item list-group-item-action bg-dark text-punk border-punk" href="/grobKaifIliBolshe">
Кайф или больше
</a>
<a class="list-group-item list-group-item-action bg-dark text-punk border-punk" href="#">
Зоопарк
</a>
<a class="list-group-item list-group-item-action bg-dark text-punk border-punk" href="#">
Новая патриотическая
</a>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<footer class="bg-black py-3 border-top border-punk mt-auto">
<div class="container">
<div class="d-flex flex-wrap justify-content-between align-items-center">
<p class="mb-0 text-punk">© 2025. Все права защищены.</p>
<nav class="d-flex align-items-center">
<a href="#" class="text-punk me-3">Политика конфиденциальности</a>
</nav>
</div>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

View File

@@ -0,0 +1,123 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/styles.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
<title>Панкуха</title>
</head>
<body class="bg-dark text-light">
<header class="sticky-top navbar navbar-expand-lg navbar-dark bg-black border-bottom border-punk px-0">
<div class="container-fluid">
<a href="/" class="navbar-brand d-flex align-items-center ms-3">
<img src="/res/logo.png" alt="Панкуха" height="60" class="me-2">
<span class="text-punk fs-4 fw-bold">Панкуха</span>
</a>
<button class="navbar-toggler me-3" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse bg-black" id="navbarContent">
<ul class="navbar-nav w-100 justify-content-end pe-4">
<li class="nav-item dropdown">
<a class="nav-link text-punk fw-bold dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
<i class="bi bi-list me-1"></i>Страницы
</a>
<ul class="dropdown-menu dropdown-menu-end bg-dark">
<li><a class="dropdown-item text-punk" href="/">Главная</a></li>
<li><a class="dropdown-item text-punk" href="/grob">Исполнитель</a></li>
<li><a class="dropdown-item text-punk" href="/grobKaifIliBolshe">Песня</a></li>
<li><a class="dropdown-item text-punk" href="/catalog">Каталог</a></li>
<li><a class="dropdown-item text-punk" href="/punkrock">Список исполнителей</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link text-punk fw-bold" href="https://vk.com/kadyshevever">
<i class="bi bi-people-fill me-1"></i>Контакты
</a>
</li>
</ul>
</div>
</div>
</header>
<main class="container-fluid my-5 flex-grow-1">
<div class="container">
<div class="card bg-dark border-punk mb-4">
<div class="card-body">
<h1 class="text-punk mb-4">Кайф или больше</h1>
<h3 class="text-light mb-3">
<div style="text-align: center;">
<img src="/res/nekrofilia.jpg" alt="uGrob" class="me-2">
</div>
<div style="text-align: center;">
<a class="text-punk" href="/grob">Гражданская оборона</a>
</h3>
</div>
</div>
</div>
<div class="card bg-dark border-punk mb-4">
<div class="card-body">
<h5 class="text-punk mb-3">Описание</h5>
<ul class="list-group list-group-flush">
<li class="list-group-item bg-dark text-light border-punk">
Была выпущена в 1987 году
</li>
<li class="list-group-item bg-dark text-light border-punk">
Входит в альбом "Некрофилия"
</li>
</ul>
</div>
</div>
<div class="card bg-dark border-punk">
<div class="card-body">
<h5 class="text-punk mb-3">Текст песни:</h5>
<pre class="text-light" style="white-space: pre-wrap;">
[Куплет 1]
Рука повисла в небе, полном до краёв
Мои ошибки устилают мой позор
Я сочно благодарен, словно кошкин блёв
И смачно богомолен, словно приговор
[Припев]
Но мне придётся выбирать
Кайф или больше
Рай или больше
Свет или больше... Хей-йо
[Куплет 2]
Я буду ласковым, как тёплый банный лист
Я буду вежливым, как битое окно
Я буду благотворен, словно онанист
Я буду зазеркален, словно всё равно
[Припев]
Но мне придётся выбирать
Кайф или больше
Рай или больше
Свет или больше...хей-йо
</pre>
</div>
</div>
</div>
</main>
<footer class="bg-black py-3 border-top border-punk mt-auto">
<div class="container">
<div class="d-flex flex-wrap justify-content-between align-items-center">
<p class="mb-0 text-punk">© 2025. Все права защищены.</p>
<nav class="d-flex align-items-center">
<a href="#" class="text-punk me-3">Политика конфиденциальности</a>
</nav>
</div>
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/styles.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
<title>Панкуха</title>
</head>
<body class="bg-dark text-light">
<div id="root"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@@ -0,0 +1,15 @@
{
"short_name": "PunkRock",
"name": "PunkRock SPA",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 80 KiB

View File

Before

Width:  |  Height:  |  Size: 91 KiB

After

Width:  |  Height:  |  Size: 91 KiB

View File

Before

Width:  |  Height:  |  Size: 89 KiB

After

Width:  |  Height:  |  Size: 89 KiB

View File

Before

Width:  |  Height:  |  Size: 240 KiB

After

Width:  |  Height:  |  Size: 240 KiB

View File

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 34 KiB

View File

Before

Width:  |  Height:  |  Size: 969 KiB

After

Width:  |  Height:  |  Size: 969 KiB

View File

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 40 KiB

View File

@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@@ -0,0 +1,189 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
--punk-primary: blueviolet;
--punk-dark: #121212;
}
a {
font-size: 16px;
font-weight: 500;
color: blueviolet;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
min-width: 320px;
min-height: 100vh;
background-color: var(--punk-dark);
color: white;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
text-align: center;
}
.lyrics {
text-align: center;
line-height: 1.8;
font-size: 1.1rem;
}
.chorus {
font-weight: bold;
margin: 1.5rem 0;
}
#app {
width: 100%;
margin: 0;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vanilla:hover {
filter: drop-shadow(0 0 2em #f7df1eaa);
}
/* Анимация карточек */
.catalog-item {
transition: transform 0.3s;
}
.catalog-item:hover {
transform: translateY(-5px);
box-shadow: 0 5px 15px rgba(138, 43, 226, 0.3);
}
.btn-punk {
background-color: blueviolet;
color: white;
border: none;
}
.btn-punk:hover {
background-color: #9d4edd;
color: white;
}
.artist-card {
transition: all 0.3s;
}
.artist-card:hover {
transform: translateY(-5px);
box-shadow: 0 5px 15px rgba(138, 43, 226, 0.4);
}
.bg-punk {
background-color: blueviolet !important;
}
/* Стиль кнопок */
.btn-outline-punk {
color: blueviolet;
border-color: blueviolet;
}
.btn-outline-punk:hover {
background-color: blueviolet;
color: white;
}
.card {
padding: 2em;
color: blueviolet;
}
.read-the-docs {
color: #888;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
.bg-punk {
background-color: var(--punk-primary) !important;
}
.text-punk {
color: var(--punk-primary) !important;
}
.border-punk {
border-color: var(--punk-primary) !important;
}
.nav-link:hover, .dropdown-item:hover {
color: white !important;
background-color: var(--punk-primary) !important;
}
.list-group-item-action:hover {
transform: translateX(5px);
transition: transform 0.3s;
}
.lead{
color: blueviolet;
text-align: center;
font-size: 20pt;
}
.navbar {
box-shadow: 0 0 15px rgba(138, 43, 226, 0.4);
}
.dropdown-menu {
background-color: #000 !important;
}
.nav-link:hover,
.nav-link:focus {
text-shadow: 0 0 8px blueviolet;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View File

@@ -0,0 +1,186 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Панк-рок | Панкуха</title>
<!-- Подключаем стили в HEAD -->
<!-- 1. Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- 2. Иконки Bootstrap -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<!-- 3. Кастомные стили -->
<link rel="stylesheet" href="/css/style.css">
</head>
<body class="d-flex flex-column min-vh-100">
<header class="sticky-top navbar navbar-expand-lg navbar-dark bg-black border-bottom border-punk px-0">
<div class="container-fluid">
<!-- Логотип и название -->
<a href="index.html" class="navbar-brand d-flex align-items-center ms-3">
<img src="res/logo.png" alt="Панкуха" height="60" class="me-2">
<span class="text-punk fs-4 fw-bold">Панкуха</span>
</a>
<!-- Кнопка для мобильных -->
<button class="navbar-toggler me-3" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Навигация -->
<div class="collapse navbar-collapse bg-black" id="navbarContent">
<ul class="navbar-nav w-100 justify-content-end pe-4">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle text-punk fw-bold" href="#" data-bs-toggle="dropdown">
<i class="bi bi-list-check me-1"></i>Страницы
</a>
<ul class="dropdown-menu dropdown-menu-dark border-punk">
<li><a class="dropdown-item text-punk" href="index.html"><i class="bi bi-house-door me-2"></i>Главная</a></li>
<li><hr class="dropdown-divider border-punk"></li>
<li><a class="dropdown-item text-punk" href="grob.html"><i class="bi bi-person-badge me-2"></i>Исполнитель</a></li>
<li><a class="dropdown-item text-punk" href="grobKaifIliBolshe.html"><i class="bi bi-music-note-beamed me-2"></i>Песня</a></li>
<li><a class="dropdown-item text-punk" href="catalog.html"><i class="bi bi-collection me-2"></i>Каталог</a></li>
</ul>
</li>
<li class="nav-item">
<a class="nav-link text-punk fw-bold" href="https://vk.com/kadyshevever">
<i class="bi bi-people-fill me-1"></i>Контакты
</a>
</li>
</ul>
</div>
</div>
</header>
<main class="container my-5 flex-grow-1">
<div class="container py-4">
<div class="card bg-dark border-punk mb-4">
<div class="card-body">
<h3 class="text-punk mb-3">
<i class="bi bi-people-fill"></i> Перечень исполнителей панк-рока
</h3>
<p class="lead text-light">
Список культовых групп жанра
</p>
<ul class="list-group list-group-flush">
<li class="list-group-item bg-dark text-punk border-punk">
<a href="grob.html" class="text-punk text-decoration-none d-flex align-items-center">
<i class="bi bi-person-badge me-2"></i> Гражданская Оборона
</a>
</li>
<li class="list-group-item bg-dark text-punk border-punk">
<a href="#" class="text-punk text-decoration-none d-flex align-items-center">
<i class="bi bi-person-badge me-2"></i> Король и Шут
</a>
</li>
<li class="list-group-item bg-dark text-punk border-punk">
<a href="#" class="text-punk text-decoration-none d-flex align-items-center">
<i class="bi bi-person-badge me-2"></i> Наив
</a>
</li>
</ul>
</div>
</div>
</div>
<!-- Форма добавления исполнителя -->
<div class="container my-5">
<div class="card bg-dark border-punk">
<div class="card-body">
<h3 class="text-punk mb-4"><i class="bi bi-person-plus"></i> Добавить исполнителя</h3>
<form id="artistForm" onsubmit="addArtist(); return false;">
<!-- Название группы -->
<div class="mb-3">
<label class="form-label text-light">Название группы</label>
<input type="text" class="form-control bg-dark text-light border-punk" id="artistName" required>
</div>
<!-- Описание -->
<div class="mb-3">
<label class="form-label text-light">Описание</label>
<textarea class="form-control bg-dark text-light border-punk" id="description" required></textarea>
</div>
<!-- Год основания -->
<div class="mb-3">
<label class="form-label text-light">Год основания</label>
<input type="number" class="form-control bg-dark text-light border-punk" id="artistYear" min="1700" max="2025">
</div>
<!-- Страна -->
<div class="mb-3">
<label class="form-label text-light">Страна</label>
<input type="text" class="form-control bg-dark text-light border-punk" id="artistCountry">
</div>
<!-- Кнопка добавления -->
<button type="submit" class="btn btn-punk mt-3">
<i class="bi bi-plus-circle"></i> Добавить исполнителя
</button>
</form>
</div>
</div>
</div>
<!-- Контейнер для карточек исполнителей -->
<div id="artistsContainer" class="row row-cols-1 row-cols-md-3 g-4 mt-4"></div>
<!-- Модальное окно для редактирования исполнителя -->
<div class="modal fade" id="editArtistModal" tabindex="-1" aria-labelledby="editArtistModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content bg-dark border-punk">
<div class="modal-header border-punk">
<h5 class="modal-title text-punk" id="editArtistModalLabel"><i class="bi bi-pencil-square me-2"></i>Редактировать исполнителя</h5>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="editArtistForm">
<div class="mb-3">
<label class="form-label text-light">Название группы</label>
<input type="text" class="form-control bg-dark text-light border-punk" id="editArtistName" required>
</div>
<div class="mb-3">
<label class="form-label text-light">Описание</label>
<textarea class="form-control bg-dark text-light border-punk" id="editDescription" required></textarea>
</div>
<div class="mb-3">
<label class="form-label text-light">Год основания</label>
<input type="number" class="form-control bg-dark text-light border-punk" id="editArtistYear" min="1700" max="2025">
</div>
<div class="mb-3">
<label class="form-label text-light">Страна</label>
<input type="text" class="form-control bg-dark text-light border-punk" id="editArtistCountry">
</div>
<input type="number" id="editArtistId" style="display: none;">
</form>
</div>
<div class="modal-footer border-punk">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-punk" id="saveEditArtist" onclick="saveEditArtist()"><i class="bi bi-save"></i> Сохранить</button>
</div>
</div>
</div>
</div>
</main>
<!-- Подвал -->
<footer class="bg-black py-3 border-top border-punk mt-auto">
<div class="container">
<div class="d-flex flex-wrap justify-content-between align-items-center">
<p class="mb-0 text-punk">© 2025. Все права защищены.</p>
<nav class="d-flex align-items-center">
<a href="#" class="text-punk me-3">Политика конфиденциальности</a>
</nav>
</div>
</div>
</footer>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<!-- Основной скрипт -->
<script type="module" src="src/js/main.js"></script>
</body>
</html>

View File

@@ -0,0 +1,38 @@
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

13
punkrock-react/src/App.js Normal file
View File

@@ -0,0 +1,13 @@
import React from 'react';
import PunkRockPage from './pages/PunkRockPage';
import './styles.css';
function App() {
return (
<div className="d-flex flex-column min-vh-100" style={{ width: '100%' }}>
<PunkRockPage />
</div>
);
}
export default App;

View File

@@ -0,0 +1,8 @@
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});

View File

@@ -0,0 +1,15 @@
import React from 'react';
const StaticPage = ({ src }) => {
return (
<div style={{ height: '100vh', width: '100vw', margin: 0, padding: 0 }}>
<iframe
src={src}
title="Static Page"
style={{ width: '100%', height: '100%', border: 'none' }}
/>
</div>
);
};
export default StaticPage;

View File

@@ -0,0 +1,34 @@
import React from 'react';
const ArtistCard = ({ artist, onEdit, onDelete }) => {
return (
<div className="col-md-4 mb-4">
<div className="card bg-dark border-punk">
<div className="card-body">
<h5 className="card-title text-punk">{artist.name}</h5>
<p className="card-text text-light">{artist.description || 'Нет описания'}</p>
<p className="card-text text-light"><small>Эпоха: {artist.epoch?.name || 'Не указана'}</small></p>
<p className="card-text text-light"><small>Страна: {artist.country?.name || 'Не указана'}</small></p>
<button
className="btn btn-outline-primary edit-btn me-2"
onClick={() => onEdit(artist)}
>
<i className="bi bi-pencil-square"></i> Изменить
</button>
<button
className="btn btn-outline-danger delete-btn"
onClick={() => {
if (window.confirm('Удалить исполнителя?')) {
onDelete(artist.id);
}
}}
>
<i className="bi bi-trash"></i> Удалить
</button>
</div>
</div>
</div>
);
};
export default ArtistCard;

View File

@@ -0,0 +1,145 @@
import React, { useState, useEffect } from 'react';
const ArtistForm = ({ countries = [], epochs = [], onSubmit, artist }) => {
const [formData, setFormData] = useState({
name: '',
description: '',
epochId: '',
countryId: ''
});
useEffect(() => {
console.log('Received countries:', countries);
console.log('Received epochs:', epochs);
if (artist) {
setFormData({
name: artist.name,
description: artist.description,
epochId: artist.epoch?.id || '',
countryId: artist.country?.id || ''
});
} else {
setFormData({
name: '',
description: '',
epochId: '',
countryId: ''
});
}
}, [artist, countries, epochs]);
const handleChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({
...prev,
[name]: value
}));
};
const handleSubmit = (e) => {
e.preventDefault();
if (!formData.name || !formData.description || !formData.epochId || !formData.countryId) {
alert('Все поля обязательны!');
return;
}
onSubmit({
name: formData.name.trim(),
description: formData.description.trim(),
epochId: Number(formData.epochId),
countryId: Number(formData.countryId)
});
if (!artist) {
setFormData({
name: '',
description: '',
epochId: '',
countryId: ''
});
}
};
return (
<div className="card bg-dark border-punk">
<div className="card-body">
<h3 className="text-punk mb-4">
<i className={`bi ${artist ? 'bi-pencil-square' : 'bi-person-plus'}`}></i>
{artist ? 'Редактировать исполнителя' : 'Добавить исполнителя'}
</h3>
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label className="form-label text-light">Название группы</label>
<input
type="text"
className="form-control bg-dark text-light border-punk"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
</div>
<div className="mb-3">
<label className="form-label text-light">Описание</label>
<textarea
className="form-control bg-dark text-light border-punk"
name="description"
value={formData.description}
onChange={handleChange}
required
/>
</div>
<div className="mb-3">
<label className="form-label text-light">Эпоха</label>
<select
className="form-select bg-dark text-light border-punk"
name="epochId"
value={formData.epochId}
onChange={handleChange}
required
>
<option value="">Выберите эпоху</option>
{epochs.length > 0 ? (
epochs.map(epoch => (
<option key={epoch.id} value={epoch.id}>{epoch.name}</option>
))
) : (
<option disabled>Нет данных</option>
)}
</select>
</div>
<div className="mb-3">
<label className="form-label text-light">Страна</label>
<select
className="form-select bg-dark text-light border-punk"
name="countryId"
value={formData.countryId}
onChange={handleChange}
required
>
<option value="">Выберите страну</option>
{countries.length > 0 ? (
countries.map(country => (
<option key={country.id} value={country.id}>{country.name}</option>
))
) : (
<option disabled>Нет данных</option>
)}
</select>
</div>
<button type="submit" className="btn btn-punk mt-3">
<i className={`bi ${artist ? 'bi-save' : 'bi-plus-circle'}`}></i>
{artist ? 'Сохранить изменения' : 'Добавить исполнителя'}
</button>
</form>
</div>
</div>
);
};
export default ArtistForm;

View File

@@ -0,0 +1,19 @@
import React from 'react';
import ArtistCard from './ArtistCard';
const ArtistList = ({ artists, onEdit, onDelete }) => {
return (
<div className="row row-cols-1 row-cols-md-3 g-4 mt-4">
{artists.map(artist => (
<ArtistCard
key={artist.id}
artist={artist}
onEdit={onEdit}
onDelete={onDelete}
/>
))}
</div>
);
};
export default ArtistList;

View File

@@ -0,0 +1,19 @@
// Footer.jsx
import React from 'react';
const Footer = () => {
return (
<footer className="bg-black py-3 border-top border-punk mt-auto">
<div className="container">
<div className="d-flex flex-wrap justify-content-between align-items-center">
<p className="mb-0 text-punk">© 2025. Все права защищены.</p>
<nav className="d-flex align-items-center">
<a href="#" className="text-punk me-3">Политика конфиденциальности</a>
</nav>
</div>
</div>
</footer>
);
};
export default Footer;

View File

@@ -0,0 +1,31 @@
// Header.jsx
import React from 'react';
const Header = () => {
return (
<header className="sticky-top navbar navbar-expand-lg navbar-dark bg-black border-bottom border-punk px-0">
<div className="container-fluid">
<a href="/" className="navbar-brand d-flex align-items-center ms-3">
<span className="text-punk fs-4 fw-bold">Панкуха</span>
</a>
<button className="navbar-toggler me-3" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse bg-black" id="navbarContent">
<ul className="navbar-nav w-100 justify-content-end pe-4">
<li className="nav-item">
<a className="nav-link text-punk fw-bold" href="https://vk.com/kadyshevever">
<i className="bi bi-people-fill me-1"></i>Контакты
</a>
</li>
</ul>
</div>
</div>
</header>
);
};
export default Header;

View File

@@ -0,0 +1,189 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
--punk-primary: blueviolet;
--punk-dark: #121212;
}
a {
font-size: 16px;
font-weight: 500;
color: blueviolet;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
min-width: 320px;
min-height: 100vh;
background-color: var(--punk-dark);
color: white;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
text-align: center;
}
.lyrics {
text-align: center;
line-height: 1.8;
font-size: 1.1rem;
}
.chorus {
font-weight: bold;
margin: 1.5rem 0;
}
#app {
width: 100%;
margin: 0;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vanilla:hover {
filter: drop-shadow(0 0 2em #f7df1eaa);
}
/* Анимация карточек */
.catalog-item {
transition: transform 0.3s;
}
.catalog-item:hover {
transform: translateY(-5px);
box-shadow: 0 5px 15px rgba(138, 43, 226, 0.3);
}
.btn-punk {
background-color: blueviolet;
color: white;
border: none;
}
.btn-punk:hover {
background-color: #9d4edd;
color: white;
}
.artist-card {
transition: all 0.3s;
}
.artist-card:hover {
transform: translateY(-5px);
box-shadow: 0 5px 15px rgba(138, 43, 226, 0.4);
}
.bg-punk {
background-color: blueviolet !important;
}
/* Стиль кнопок */
.btn-outline-punk {
color: blueviolet;
border-color: blueviolet;
}
.btn-outline-punk:hover {
background-color: blueviolet;
color: white;
}
.card {
padding: 2em;
color: blueviolet;
}
.read-the-docs {
color: #888;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
.bg-punk {
background-color: var(--punk-primary) !important;
}
.text-punk {
color: var(--punk-primary) !important;
}
.border-punk {
border-color: var(--punk-primary) !important;
}
.nav-link:hover, .dropdown-item:hover {
color: white !important;
background-color: var(--punk-primary) !important;
}
.list-group-item-action:hover {
transform: translateX(5px);
transition: transform 0.3s;
}
.lead{
color: blueviolet;
text-align: center;
font-size: 20pt;
}
.navbar {
box-shadow: 0 0 15px rgba(138, 43, 226, 0.4);
}
.dropdown-menu {
background-color: #000 !important;
}
.nav-link:hover,
.nav-link:focus {
text-shadow: 0 0 8px blueviolet;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View File

@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

View File

@@ -0,0 +1,51 @@
import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-icons/font/bootstrap-icons.css';
import { BrowserRouter, Routes, Route, useLocation } from 'react-router-dom';
import App from './App';
// Компонент для редиректа на статические страницы
const RedirectToStatic = () => {
const location = useLocation();
const hasRedirected = React.useRef(false);
React.useEffect(() => {
// Редирект только если маршрут не заканчивается на .html и редирект ещё не выполнен
if (!hasRedirected.current && !location.pathname.endsWith('.html')) {
let targetPath = location.pathname === '/' ? '/index.html' : `${location.pathname}.html`;
hasRedirected.current = true; // Устанавливаем флаг, чтобы избежать повторного редиректа
window.location.replace(targetPath); // Прямой редирект на статический файл
}
}, [location.pathname]);
// Ничего не рендерим
return null;
};
// Компонент для рендеринга React-логики
const RootComponent = () => {
return (
<div className="d-flex flex-column min-vh-100" style={{ width: '100%' }}>
<App />
</div>
);
};
// Рендеринг React только для маршрута /punkrock
const rootElement = document.getElementById('root');
if (rootElement) {
const root = ReactDOM.createRoot(rootElement);
root.render(
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route path="/punkrock" element={<RootComponent />} />
<Route path="/*" element={<RedirectToStatic />} />
</Routes>
</BrowserRouter>
</React.StrictMode>
);
} else {
console.error('Root element not found. Ensure public/index.html contains <div id="root">');
}

View File

@@ -0,0 +1,208 @@
// Основной JavaScript код для работы с исполнителями
const API_URL = 'http://localhost:8080/api';
// Загрузка данных при загрузке страницы
document.addEventListener('DOMContentLoaded', function() {
loadArtists();
loadCountries();
loadEpochs();
});
// Загрузка исполнителей
async function loadArtists() {
try {
const response = await fetch(`${API_URL}/artists`);
const artists = await response.json();
displayArtists(artists);
} catch (error) {
console.error('Ошибка загрузки исполнителей:', error);
}
}
// Загрузка стран
async function loadCountries() {
try {
const response = await fetch(`${API_URL}/countries`);
const countries = await response.json();
console.log('Загружены страны:', countries);
} catch (error) {
console.error('Ошибка загрузки стран:', error);
}
}
// Загрузка эпох
async function loadEpochs() {
try {
const response = await fetch(`${API_URL}/epochs`);
const epochs = await response.json();
console.log('Загружены эпохи:', epochs);
} catch (error) {
console.error('Ошибка загрузки эпох:', error);
}
}
// Отображение исполнителей
function displayArtists(artists) {
const container = document.getElementById('artistsContainer');
container.innerHTML = '';
artists.forEach(artist => {
const artistCard = createArtistCard(artist);
container.appendChild(artistCard);
});
}
// Создание карточки исполнителя
function createArtistCard(artist) {
const col = document.createElement('div');
col.className = 'col-md-4 mb-4';
col.innerHTML = `
<div class="card bg-dark border-punk">
<div class="card-body">
<h5 class="card-title text-punk">${artist.name}</h5>
<p class="card-text text-light">${artist.description || 'Нет описания'}</p>
<p class="card-text text-light"><small>Эпоха ID: ${artist.epochId || 'Не указана'}</small></p>
<p class="card-text text-light"><small>Страна ID: ${artist.countryId || 'Не указана'}</small></p>
<button class="btn btn-outline-primary edit-btn me-2" onclick="editArtist(${artist.id})">
<i class="bi bi-pencil-square"></i> Изменить
</button>
<button class="btn btn-outline-danger delete-btn" onclick="deleteArtist(${artist.id})">
<i class="bi bi-trash"></i> Удалить
</button>
</div>
</div>
`;
return col;
}
// Редактирование исполнителя
function editArtist(id) {
// ID теперь числовой
console.log('Редактирование исполнителя с ID:', id, 'тип:', typeof id);
// Заполняем форму данными исполнителя
document.getElementById('editArtistId').value = id;
// Здесь можно загрузить данные исполнителя и заполнить форму
// Пока что просто открываем модальное окно
const modal = new bootstrap.Modal(document.getElementById('editArtistModal'));
modal.show();
}
// Удаление исполнителя
async function deleteArtist(id) {
// ID теперь числовой
console.log('Удаление исполнителя с ID:', id, 'тип:', typeof id);
if (confirm('Удалить исполнителя?')) {
try {
const response = await fetch(`${API_URL}/artists/${id}`, {
method: 'DELETE'
});
if (response.ok) {
loadArtists(); // Перезагружаем список
} else {
alert('Ошибка удаления исполнителя');
}
} catch (error) {
console.error('Ошибка удаления:', error);
alert('Ошибка удаления исполнителя');
}
}
}
// Сохранение изменений исполнителя
async function saveEditArtist() {
const id = parseInt(document.getElementById('editArtistId').value);
const name = document.getElementById('editArtistName').value;
const description = document.getElementById('editDescription').value;
const year = document.getElementById('editArtistYear').value;
const country = document.getElementById('editArtistCountry').value;
console.log('Сохранение исполнителя с ID:', id, 'тип:', typeof id);
if (!name || !description) {
alert('Все поля обязательны!');
return;
}
try {
const response = await fetch(`${API_URL}/artists/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: name,
description: description,
epochId: 1, // Пока что статическое значение
countryId: 1 // Пока что статическое значение
})
});
if (response.ok) {
const modal = bootstrap.Modal.getInstance(document.getElementById('editArtistModal'));
modal.hide();
loadArtists(); // Перезагружаем список
} else {
alert('Ошибка сохранения исполнителя');
}
} catch (error) {
console.error('Ошибка сохранения:', error);
alert('Ошибка сохранения исполнителя');
}
}
// Добавление нового исполнителя
async function addArtist() {
const name = document.getElementById('artistName').value;
const description = document.getElementById('description').value;
const year = document.getElementById('artistYear').value;
const country = document.getElementById('artistCountry').value;
if (!name || !description) {
alert('Все поля обязательны!');
return;
}
try {
const response = await fetch(`${API_URL}/artists`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: name,
description: description,
epochId: 1, // Пока что статическое значение
countryId: 1 // Пока что статическое значение
})
});
if (response.ok) {
document.getElementById('artistForm').reset();
loadArtists(); // Перезагружаем список
} else {
alert('Ошибка добавления исполнителя');
}
} catch (error) {
console.error('Ошибка добавления:', error);
alert('Ошибка добавления исполнителя');
}
}
// Привязка событий
document.addEventListener('DOMContentLoaded', function() {
// Кнопка сохранения редактирования
document.getElementById('saveEditArtist').addEventListener('click', saveEditArtist);
// Кнопка добавления исполнителя
document.getElementById('artistForm').addEventListener('submit', function(e) {
e.preventDefault();
addArtist();
});
});

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

Some files were not shown because too many files have changed in this diff Show More