Initial commit

parent 48633912
File added
/mvnw text eol=lf
*.cmd text eol=crlf
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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
#
# http://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.
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
### Чирцов Т А Группа 1.1
# Отчет по лабораторной работе "Task Management System"
## Описание работы
В ходе выполнения работы был создан RESTful веб-сервис для управления задачами с использованием Spring Boot. Приложение поддерживает базовые CRUD-операции: создание, редактирование, удаление и просмотр задач.
## Ход выполнения
1. **Создание проекта:**
- Проект был создан с помощью Spring Initializr с выбранными зависимостями: `Spring Web`, `Spring Data JPA`, `H2 Database`, `Spring Security`.
- Проект был импортирован в среду разработки IntelliJ IDEA.
2. **Создание модели задачи:**
- Создан класс `Task` с полями `id`, `title`, `description`, `status`, `createdAt`.
- Для аннотаций использовались `@Entity`, `@Id`, `@GeneratedValue(strategy = GenerationType.IDENTITY)`, `@Column`.
- Добавлены геттеры, сеттеры и методы `equals`, `hashCode`, `toString` для корректного сравнения объектов.
3. **Создание репозитория:**
- Создан интерфейс `TaskRepository`, который наследуется от `JpaRepository` для доступа к данным базы.
4. **Создание контроллера:**
- Создан класс `TaskController` с аннотацией `@RestController` и маршрутами CRUD операций.
- Методы контроллера:
- `@GetMapping("/api/tasks")` — получение списка всех задач.
- `@PostMapping("/api/tasks")` — добавление новой задачи.
- `@PutMapping("/api/tasks/{id}")` — обновление задачи по ID.
- `@DeleteMapping("/api/tasks/{id}")` — удаление задачи по ID.
- Добавлена обработка ошибок с возвратом корректных HTTP-кодов (`404 Not Found`, `201 Created`, `200 OK`, `204 No Content`).
5. **Настройка базы данных:**
- Настроен файл `application.yml` для использования базы данных H2 в режиме "in-memory".
- Включена консоль H2 для проверки данных по адресу [http://localhost:8080/h2-console](http://localhost:8080/h2-console).
6. **Добавление безопасности:**
- В `pom.xml` добавлена зависимость `spring-boot-starter-security`.
- Создан класс `SecurityConfig` для настройки базовой аутентификации.
- В `SecurityConfig`:
- Включена `HTTP Basic` аутентификация.
- Добавлен пользователь с логином `admin` и паролем `admin123`.
- Для упрощения тестирования CSRF защита была отключена.
## Результаты тестирования
Тестирование проводилось с использованием Postman. Были протестированы следующие эндпоинты:
1. **Создание задачи (POST /api/tasks)**:
```json
{
"title": "First Task",
"description": "Description of the first task",
"status": "Pending"
}
```
**Результат:** HTTP 201 Created, задача успешно добавлена.
2. **Получение всех задач (GET /api/tasks)**:
**Результат:** HTTP 200 OK, возвращается список задач.
3. **Обновление задачи (PUT /api/tasks/1)**:
```json
{
"title": "Updated Task",
"description": "Updated description",
"status": "Completed"
}
```
**Результат:** HTTP 200 OK, данные задачи обновлены.
4. **Удаление задачи (DELETE /api/tasks/1)**:
**Результат:** HTTP 204 No Content, задача успешно удалена.
5. **Получение несуществующей задачи:**
**Результат:** HTTP 404 Not Found.
## Выводы
В ходе работы было создано полноценное RESTful-приложение с поддержкой аутентификации и всех CRUD операций для управления задачами. Настроена база данных H2 и реализована базовая защита через Spring Security.
Для тестирования использовались запросы через Postman и проверка базы данных через консоль H2.
## Скриншоты
![task1.png](images/task1.png)
![task2.png](images/task2.png)
![controller1.png](images/controller1.png)
![controller2.png](images/controller2.png)
![application.png](images/application.png)
\ No newline at end of file
This diff is collapsed.
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.2
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>taskmanagement</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Task Management System</name>
<description>RESTful web application for managing tasks.</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>23</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.15</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
File added
package com.example.taskmanagement;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TaskManagementSystemApplication {
public static void main(String[] args) {
SpringApplication.run(TaskManagementSystemApplication.class, args);
}
}
package com.example.taskmanagement.controller;
import com.example.taskmanagement.model.Task;
import com.example.taskmanagement.repository.TaskRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import java.time.LocalDateTime;
import java.util.List;
@RestController
@RequestMapping("/api/tasks")
public class TaskController {
private final TaskRepository taskRepository;
@Autowired
public TaskController(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
@GetMapping
public ResponseEntity<List<Task>> getAllTasks() {
List<Task> tasks = taskRepository.findAll();
return tasks.isEmpty() ? ResponseEntity.noContent().build() : ResponseEntity.ok(tasks);
}
@PostMapping
public ResponseEntity<Task> createTask(@RequestBody Task task) {
task.setCreatedAt(LocalDateTime.now());
Task savedTask = taskRepository.save(task);
return ResponseEntity.status(HttpStatus.CREATED).body(savedTask);
}
@PutMapping("/{id}")
public ResponseEntity<Task> updateTask(@PathVariable Long id, @RequestBody Task updatedTask) {
return taskRepository.findById(id)
.map(task -> {
task.setTitle(updatedTask.getTitle());
task.setDescription(updatedTask.getDescription());
task.setStatus(updatedTask.getStatus());
Task savedTask = taskRepository.save(task);
return ResponseEntity.ok(savedTask);
})
.orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).body(null));
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteTask(@PathVariable Long id) {
if (taskRepository.existsById(id)) {
taskRepository.deleteById(id);
return ResponseEntity.noContent().build();
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
}
}
package com.example.taskmanagement.model;
import jakarta.persistence.*;
import java.time.LocalDateTime;
import java.util.Objects;
@Entity
@Table(name = "tasks")
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String title;
@Column(length = 500)
private String description;
@Column(nullable = false)
private String status;
@Column(name = "created_at", updatable = false)
private LocalDateTime createdAt;
public Task() {
}
public Task(String title, String description, String status, LocalDateTime createdAt) {
this.title = title;
this.description = description;
this.status = status;
this.createdAt = createdAt;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Task task = (Task) o;
return Objects.equals(id, task.id) &&
Objects.equals(title, task.title) &&
Objects.equals(description, task.description) &&
Objects.equals(status, task.status) &&
Objects.equals(createdAt, task.createdAt);
}
@Override
public int hashCode() {
return Objects.hash(id, title, description, status, createdAt);
}
@Override
public String toString() {
return "Task{" +
"id=" + id +
", title='" + title + '\'' +
", description='" + description + '\'' +
", status='" + status + '\'' +
", createdAt=" + createdAt +
'}';
}
}
package com.example.taskmanagement.repository;
import com.example.taskmanagement.model.Task;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface TaskRepository extends JpaRepository<Task, Long> {
// В этом интерфейсе можно добавить пользовательские методы, если потребуется
}
spring:
application:
name: Task Management System
datasource:
url: jdbc:h2:mem:taskdb
driver-class-name: org.h2.Driver
username: sa
password: password
jpa:
hibernate:
ddl-auto: update
h2:
console:
enabled: true
security:
user:
name: admin
password: admin
package com.example.taskmanagement;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class TaskManagementSystemApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment