3 Commits

Author SHA1 Message Date
a3dcf8e887 Готовая ЛР с отчетом 2025-09-11 14:17:53 +04:00
f2d5e404ed Наговнокодил 2025-09-10 11:52:51 +04:00
30dcc1a649 Сделал 1 Лабораторную 2025-09-07 15:18:38 +04:00
26 changed files with 1458 additions and 81 deletions

3
ip-backend-labs/.gitattributes vendored Normal file
View File

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

37
ip-backend-labs/.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/

View File

@@ -0,0 +1,34 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.5.5'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'io.github.f1rstteam'
version = '0.0.1-SNAPSHOT'
description = 'Demo project for Spring Boot'
defaultTasks "bootRun"
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.5'
implementation("com.fasterxml.jackson.core:jackson-databind")
implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
tasks.named('test') {
useJUnitPlatform()
}

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
ip-backend-labs/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
ip-backend-labs/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

View File

@@ -0,0 +1 @@
[{"id":10,"text":"324234","image":"","group":"Моя группа","likes":3,"comments":2,"shares":2,"createdAt":[2025,9,7,14,57,10,10870800]},{"id":11,"text":"53456453","image":"","group":"Моя группа","likes":0,"comments":0,"shares":0,"createdAt":[2025,9,7,14,57,11,853363900]},{"id":16,"text":"11111111111","image":"","group":"Моя группа","likes":0,"comments":0,"shares":0,"createdAt":[2025,9,11,12,32,41,210363800]},{"id":17,"text":"673453","image":"","group":"Моя группа","likes":0,"comments":0,"shares":0,"createdAt":[2025,9,11,12,36,36,393719200]}]

View File

@@ -0,0 +1 @@
rootProject.name = 'ip-backend-labs'

View File

@@ -0,0 +1,37 @@
package io.github.f1rstteam.ip_backend_labs.DTO.Mapping;
import java.time.LocalDateTime;
import org.springframework.stereotype.Component;
import io.github.f1rstteam.ip_backend_labs.DTO.PostDTO;
import io.github.f1rstteam.ip_backend_labs.model.Post;
@Component
public class PostMapper {
public PostDTO toDTO(Post post) {
PostDTO dto = new PostDTO();
dto.setId(post.getId());
dto.setText(post.getText());
dto.setImage(post.getImage());
dto.setGroup(post.getGroup());
dto.setLikes(post.getLikes());
dto.setComments(post.getComments());
dto.setShares(post.getShares());
dto.setCreatedAt(post.getCreatedAt());
return dto;
}
public Post toEntity(PostDTO postDTO) {
Post post = new Post();
post.setId(postDTO.getId() != null ? postDTO.getId() : null);
post.setText(postDTO.getText() != null ? postDTO.getText() : "");
post.setImage(postDTO.getImage() != null ? postDTO.getImage() : "");
post.setGroup(postDTO.getGroup() != null ? postDTO.getGroup() : "Моя группа");
post.setLikes(postDTO.getLikes() >= 0 ? postDTO.getLikes() : 0);
post.setComments(postDTO.getComments() >= 0 ? postDTO.getComments() : 0);
post.setShares(postDTO.getShares() >= 0 ? postDTO.getShares() : 0);
post.setCreatedAt(postDTO.getCreatedAt() != null ? postDTO.getCreatedAt() : LocalDateTime.now());
return post;
}
}

View File

@@ -0,0 +1,45 @@
package io.github.f1rstteam.ip_backend_labs.DTO;
import java.time.LocalDateTime;
public class PostDTO {
private Long id;
private String text;
private String image;
private String group;
private int likes;
private int comments;
private int shares;
private LocalDateTime createdAt;
public PostDTO() {}
public PostDTO(Long id, String text, String image, String group, int likes, int comments, int shares, LocalDateTime createdAt) {
this.id = id;
this.text = text;
this.image = image;
this.group = group;
this.likes = likes;
this.comments = comments;
this.shares = shares;
this.createdAt = createdAt;
}
public Long getId() { return id; }
public String getText() { return text; }
public String getImage() { return image; }
public String getGroup() { return group; }
public int getLikes() { return likes; }
public int getComments() { return comments; }
public int getShares() { return shares; }
public LocalDateTime getCreatedAt() { return createdAt; }
public void setId(Long id) { this.id = id; }
public void setText(String text) { this.text = text; }
public void setImage(String image) { this.image = image; }
public void setGroup(String group) { this.group = group; }
public void setLikes(int likes) { this.likes = likes; }
public void setComments(int comments) { this.comments = comments; }
public void setShares(int shares) { this.shares = shares; }
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
}

View File

@@ -0,0 +1,13 @@
package io.github.f1rstteam.ip_backend_labs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class InternetProgrammingBackendLabsApplication {
public static void main(String[] args) {
SpringApplication.run(InternetProgrammingBackendLabsApplication.class, args);
}
}

View File

@@ -0,0 +1,146 @@
package io.github.f1rstteam.ip_backend_labs.Service;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.github.f1rstteam.ip_backend_labs.model.Post;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
@Service
public class JsonPostService {
private static final String STORAGE_FILE = "posts.json";
private final ObjectMapper objectMapper = new ObjectMapper();
private List<Post> posts = new ArrayList<>();
private final AtomicLong counter = new AtomicLong(1);
public JsonPostService() {
objectMapper.registerModule(new JavaTimeModule());
}
@PostConstruct
public void loadPosts() {
try {
File file = new File(STORAGE_FILE);
if (file.exists()) {
CollectionType listType = objectMapper.getTypeFactory()
.constructCollectionType(List.class, Post.class);
posts = objectMapper.readValue(file, listType);
System.out.println("Загружено " + posts.size() + " постов из файла");
if (!posts.isEmpty()) {
long maxId = posts.stream()
.mapToLong(Post::getId)
.max()
.orElse(0);
counter.set(maxId + 1);
}
} else {
posts = getInitialPosts();
savePostsImmediately();
System.out.println("Созданы начальные посты: " + posts.size());
}
} catch (IOException e) {
System.out.println("Ошибка загрузки файла: " + e.getMessage());
posts = getInitialPosts();
}
}
@PreDestroy
public void savePosts() {
try {
objectMapper.writeValue(new File(STORAGE_FILE), posts);
System.out.println("Сохранено " + posts.size() + " постов в файл");
} catch (IOException e) {
System.out.println("Ошибка сохранения файла: " + e.getMessage());
}
}
public void savePostsImmediately() {
savePosts();
}
private List<Post> getInitialPosts() {
List<Post> initialPosts = new ArrayList<>();
LocalDateTime now = LocalDateTime.now();
initialPosts.add(new Post(
1L,
"Первый мем",
"/images/meme1.jpg",
"Какая-то группа 1",
8, 2, 1,
now.minusDays(2)
));
initialPosts.add(new Post(
2L,
"Второй мем",
"/images/meme2.jpg",
"Какая-то группа 2",
785, 102, 14,
now.minusDays(2)
));
return initialPosts;
}
public List<Post> getAllPosts() {
return new ArrayList<>(posts);
}
public Post getPostById(Long id) {
return posts.stream()
.filter(post -> post.getId().equals(id))
.findFirst()
.orElseThrow(() -> new RuntimeException("Post not found"));
}
public Post createPost(Post post) {
post.setId(counter.getAndIncrement());
post.setCreatedAt(LocalDateTime.now());
posts.add(post);
savePostsImmediately();
return post;
}
public Post updatePost(Long id, Post updatedPost) {
Post post = getPostById(id);
post.setText(updatedPost.getText());
post.setImage(updatedPost.getImage());
post.setGroup(updatedPost.getGroup());
post.setLikes(updatedPost.getLikes());
post.setComments(updatedPost.getComments());
post.setShares(updatedPost.getShares());
savePostsImmediately();
return post;
}
public void deletePost(Long id) {
Post post = getPostById(id);
posts.remove(post);
savePostsImmediately();
}
public Post likePost(Long id) {
Post post = getPostById(id);
post.setLikes(post.getLikes() + 1);
savePostsImmediately();
return post;
}
}

View File

@@ -0,0 +1,23 @@
package io.github.f1rstteam.ip_backend_labs.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**") //запросы ко всем API endpoints
.allowedOrigins("http://localhost:3000") //React фронт
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true);
}
};
}
}

View File

@@ -0,0 +1,133 @@
package io.github.f1rstteam.ip_backend_labs.controllers;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
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 io.github.f1rstteam.ip_backend_labs.DTO.PostDTO;
import io.github.f1rstteam.ip_backend_labs.DTO.Mapping.PostMapper;
import io.github.f1rstteam.ip_backend_labs.Service.JsonPostService;
import io.github.f1rstteam.ip_backend_labs.model.Post;
@RestController
@RequestMapping("/api/posts")
public class PostControllerDTO {
private final JsonPostService postService;
private final PostMapper postMapper;
private final List<PostDTO> postsDTO = new ArrayList<>();
public PostControllerDTO(JsonPostService postService, PostMapper postMapper) {
this.postService = postService;
this.postMapper = postMapper;
initializePredefinedData();
}
private void initializePredefinedData() {
postsDTO.addAll(postService.getAllPosts().stream()
.map(postMapper::toDTO)
.collect(Collectors.toList()));
}
@GetMapping
public List<PostDTO> getAllPosts() {
return postService.getAllPosts().stream()
.map(postMapper::toDTO)
.collect(Collectors.toList());
}
@GetMapping("/{postId}")
public PostDTO getPostById(@PathVariable("postId") Long id) {
return postMapper.toDTO(postService.getPostById(id));
}
@PostMapping
public PostDTO createPost(@RequestBody PostDTO postDTO) {
Post post = postMapper.toEntity(postDTO);
Post savedPost = postService.createPost(post);
return postMapper.toDTO(savedPost);
}
@PutMapping("/{postId}")
public PostDTO updatePost(@PathVariable("postId") Long id, @RequestBody PostDTO postDTO) {
Post existingPost = postService.getPostById(id);
existingPost.setText(postDTO.getText());
existingPost.setImage(postDTO.getImage());
existingPost.setGroup(postDTO.getGroup());
existingPost.setLikes(postDTO.getLikes());
existingPost.setComments(postDTO.getComments());
existingPost.setShares(postDTO.getShares());
Post updatedPost = postService.updatePost(id, existingPost);
return postMapper.toDTO(updatedPost);
}
@DeleteMapping("/{postId}")
public void deletePost(@PathVariable("postId") Long id) {
postService.deletePost(id);
}
@PatchMapping("/{postId}/like")
public PostDTO likePost(@PathVariable("postId") Long id) {
Post existingPost = postService.getPostById(id);
existingPost.setLikes(existingPost.getLikes() + 1);
Post updatedPost = postService.updatePost(id, existingPost);
return postMapper.toDTO(updatedPost);
}
@PatchMapping("/{postId}/dislike")
public PostDTO dislikePost(@PathVariable("postId") Long id) {
Post existingPost = postService.getPostById(id);
existingPost.setLikes(Math.max(0, existingPost.getLikes() - 1));
Post updatedPost = postService.updatePost(id, existingPost);
return postMapper.toDTO(updatedPost);
}
@PatchMapping("/{postId}/comment")
public PostDTO commentPost(@PathVariable("postId") Long id) {
Post existingPost = postService.getPostById(id);
existingPost.setComments(existingPost.getComments() + 1);
Post updatedPost = postService.updatePost(id, existingPost);
return postMapper.toDTO(updatedPost);
}
@PatchMapping("/{postId}/share")
public PostDTO sharePost(@PathVariable("postId") Long id) {
Post existingPost = postService.getPostById(id);
existingPost.setShares(existingPost.getShares() + 1);
Post updatedPost = postService.updatePost(id, existingPost);
return postMapper.toDTO(updatedPost);
}
@PatchMapping("/{postId}/unshare")
public PostDTO unsharePost(@PathVariable("postId") Long id) {
Post existingPost = postService.getPostById(id);
existingPost.setShares(Math.max(0, existingPost.getShares() - 1));
Post updatedPost = postService.updatePost(id, existingPost);
return postMapper.toDTO(updatedPost);
}
}

View File

@@ -0,0 +1,53 @@
package io.github.f1rstteam.ip_backend_labs.model;
import java.time.LocalDateTime;
public class Post {
private Long id;
private String text;
private String image;
private String group;
private int likes;
private int comments;
private int shares;
private LocalDateTime createdAt;
public Post() {}
public Post(Long id, String text, String image, String group, int likes, int comments, int shares, LocalDateTime createdAt) {
this.id = id;
this.text = text;
this.image = image;
this.group = group;
this.likes = likes;
this.comments = comments;
this.shares = shares;
this.createdAt = createdAt;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getText() { return text; }
public void setText(String text) { this.text = text; }
public String getImage() { return image; }
public void setImage(String image) { this.image = image; }
public String getGroup() { return group; }
public void setGroup(String group) { this.group = group; }
public int getLikes() { return likes; }
public void setLikes(int likes) { this.likes = likes; }
public int getComments() { return comments; }
public void setComments(int comments) { this.comments = comments; }
public int getShares() { return shares; }
public void setShares(int shares) { this.shares = shares; }
public LocalDateTime getCreatedAt() { return createdAt; }
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
}

View File

@@ -0,0 +1,5 @@
spring.main.banner-mode=off
spring.application.name=Internet Programming Backend Labs
# Available levels: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
logging.level.ru.ulstu.is.server=DEBUG

View File

@@ -0,0 +1,13 @@
package io.github.f1rstteam.ip_backend_labs;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class InternetProgrammingBackendLabsApplicationTests {
@Test
void contextLoads() {
}
}

View File

@@ -0,0 +1 @@
[{"id":1,"title":"4534","description":"45","completed":false}]

View File

@@ -12,7 +12,7 @@
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.9.0",
"axios": "^1.11.0",
"bootstrap": "^5.3.6",
"bootstrap-icons": "^1.13.1",
"json-server": "^1.0.0-beta.3",
@@ -5215,25 +5215,26 @@
}
},
"node_modules/axios": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",
"integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",
"version": "1.11.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.11.0.tgz",
"integrity": "sha512-1Lx3WLFQWm3ooKDYZD1eXmoGO9fxYQjrycfHFC8P0sCfQVXyROp0p9PFWBehewBOdCwHc+f/b8I0fMto5eSfwA==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"form-data": "^4.0.4",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/axios/node_modules/form-data": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
"integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==",
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz",
"integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {

View File

@@ -3,17 +3,16 @@
"version": "0.1.0",
"private": true,
"dependencies": {
"@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",
"axios": "^1.9.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^14.5.2",
"axios": "^1.6.0",
"bootstrap": "^5.3.6",
"bootstrap-icons": "^1.13.1",
"json-server": "^1.0.0-beta.3",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router-dom": "^7.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.8.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
@@ -42,4 +41,4 @@
"last 1 safari version"
]
}
}
}

View File

@@ -0,0 +1,209 @@
.task-manager {
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.loading {
text-align: center;
font-size: 18px;
color: #666;
margin: 50px 0;
}
.empty-state {
text-align: center;
padding: 40px;
color: #888;
font-size: 16px;
border: 2px dashed #ddd;
border-radius: 8px;
}
/* Формы */
.add-task-form {
background: #f8f9fa;
padding: 20px;
border-radius: 8px;
margin-bottom: 30px;
border: 1px solid #e9ecef;
}
.form-group {
margin-bottom: 15px;
}
.form-input, .form-textarea {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
.form-input:focus, .form-textarea:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}
.form-textarea {
resize: vertical;
min-height: 60px;
}
/* Кнопки */
.btn {
padding: 8px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
margin: 5px;
transition: all 0.2s;
}
.btn:hover {
transform: translateY(-1px);
}
.btn-primary {
background: #007bff;
color: white;
}
.btn-success {
background: #28a745;
color: white;
}
.btn-warning {
background: #ffc107;
color: black;
}
.btn-danger {
background: #dc3545;
color: white;
}
.btn-info {
background: #17a2b8;
color: white;
}
.btn-secondary {
background: #6c757d;
color: white;
}
/* Список задач */
.tasks-list {
margin-top: 30px;
}
.task-item {
background: white;
border: 1px solid #e9ecef;
border-radius: 8px;
padding: 20px;
margin-bottom: 15px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
transition: all 0.3s;
}
.task-item:hover {
box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}
.task-item.completed {
background: #f8fff9;
border-color: #28a745;
}
.task-item.completed .task-title {
text-decoration: line-through;
color: #28a745;
}
.task-content {
margin-bottom: 15px;
}
.task-title {
margin: 0 0 10px 0;
color: #333;
font-size: 18px;
}
.task-description {
margin: 0 0 10px 0;
color: #666;
line-height: 1.5;
}
.task-status {
font-size: 14px;
color: #888;
}
.task-actions {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.edit-form {
display: flex;
flex-direction: column;
gap: 10px;
}
.edit-actions {
display: flex;
gap: 10px;
}
/* Статус подключения */
.connection-status {
position: fixed;
bottom: 20px;
right: 20px;
padding: 10px 15px;
background: white;
border-radius: 20px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
}
.status-indicator {
font-size: 16px;
}
.status-indicator.connected {
color: #28a745;
}
.status-indicator.disconnected {
color: #dc3545;
}
/* Адаптивность */
@media (max-width: 768px) {
.task-manager {
padding: 10px;
}
.task-actions {
flex-direction: column;
}
.btn {
width: 100%;
margin: 2px 0;
}
}

View File

@@ -0,0 +1,206 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import './TaskManager.css';
const TaskManager = () => {
const [tasks, setTasks] = useState([]);
const [newTask, setNewTask] = useState({
title: '',
description: '',
completed: false
});
const [editingTask, setEditingTask] = useState(null);
const [loading, setLoading] = useState(true);
const API_BASE_URL = 'http://localhost:8080/api/tasks';
// Получить все задачи
const fetchTasks = async () => {
try {
setLoading(true);
const response = await axios.get(API_BASE_URL);
setTasks(response.data);
} catch (error) {
console.error('Ошибка при загрузке задач:', error);
alert('Не удалось загрузить задачи. Проверьте, запущен ли backend на порту 8080');
} finally {
setLoading(false);
}
};
// Создать новую задачу
const createTask = async () => {
if (!newTask.title.trim()) {
alert('Введите название задачи!');
return;
}
try {
const response = await axios.post(API_BASE_URL, newTask);
setTasks([...tasks, response.data]);
setNewTask({ title: '', description: '', completed: false });
} catch (error) {
console.error('Ошибка при создании задачи:', error);
}
};
// Обновить задачу
const updateTask = async (id, updatedData) => {
try {
const response = await axios.put(`${API_BASE_URL}/${id}`, updatedData);
setTasks(tasks.map(task => task.id === id ? response.data : task));
setEditingTask(null);
} catch (error) {
console.error('Ошибка при обновлении задачи:', error);
}
};
// Удалить задачу
const deleteTask = async (id) => {
if (!window.confirm('Удалить эту задачу?')) return;
try {
await axios.delete(`${API_BASE_URL}/${id}`);
setTasks(tasks.filter(task => task.id !== id));
} catch (error) {
console.error('Ошибка при удалении задачи:', error);
}
};
// Переключить статус выполнения
const toggleComplete = async (task) => {
await updateTask(task.id, {
...task,
completed: !task.completed
});
};
useEffect(() => {
fetchTasks();
}, []);
if (loading) {
return <div className="loading">Загрузка задач...</div>;
}
return (
<div className="task-manager">
<h1>🚀 Менеджер задач</h1>
<p>Лабораторная работа по Интернет программированию</p>
{/* Форма добавления новой задачи */}
<div className="add-task-form">
<h2>Добавить новую задачу</h2>
<div className="form-group">
<input
type="text"
placeholder="Название задачи *"
value={newTask.title}
onChange={(e) => setNewTask({...newTask, title: e.target.value})}
className="form-input"
/>
</div>
<div className="form-group">
<textarea
placeholder="Описание задачи"
value={newTask.description}
onChange={(e) => setNewTask({...newTask, description: e.target.value})}
className="form-textarea"
rows="3"
/>
</div>
<button onClick={createTask} className="btn btn-primary">
Добавить задачу
</button>
</div>
{/* Список задач */}
<div className="tasks-list">
<h2>Список задач ({tasks.length})</h2>
{tasks.length === 0 ? (
<div className="empty-state">
📝 Нет задач. Добавьте первую задачу!
</div>
) : (
tasks.map(task => (
<div key={task.id} className={`task-item ${task.completed ? 'completed' : ''}`}>
{editingTask === task.id ? (
// Режим редактирования
<div className="edit-form">
<input
type="text"
value={editingTask.title}
onChange={(e) => setEditingTask({...editingTask, title: e.target.value})}
className="form-input"
/>
<textarea
value={editingTask.description}
onChange={(e) => setEditingTask({...editingTask, description: e.target.value})}
className="form-textarea"
rows="2"
/>
<div className="edit-actions">
<button
onClick={() => updateTask(task.id, editingTask)}
className="btn btn-success"
>
💾 Сохранить
</button>
<button
onClick={() => setEditingTask(null)}
className="btn btn-secondary"
>
Отмена
</button>
</div>
</div>
) : (
// Режим просмотра
<>
<div className="task-content">
<h3 className="task-title">{task.title}</h3>
<p className="task-description">{task.description}</p>
<div className="task-status">
Статус: {task.completed ? '✅ Выполнено' : '⏳ В процессе'}
</div>
</div>
<div className="task-actions">
<button
onClick={() => toggleComplete(task)}
className={`btn ${task.completed ? 'btn-warning' : 'btn-success'}`}
>
{task.completed ? '↩️ Возобновить' : '✅ Завершить'}
</button>
<button
onClick={() => setEditingTask({...task})}
className="btn btn-info"
>
Редактировать
</button>
<button
onClick={() => deleteTask(task.id)}
className="btn btn-danger"
>
🗑 Удалить
</button>
</div>
</>
)}
</div>
))
)}
</div>
{/* Статус подключения */}
<div className="connection-status">
<div className={`status-indicator ${tasks.length > 0 ? 'connected' : 'disconnected'}`}>
</div>
Backend: {tasks.length > 0 ? 'Подключен' : 'Не подключен'}
</div>
</div>
);
};
export default TaskManager;

View File

@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react';
import axios from 'axios';
const API_URL = 'http://localhost:3000/posts';
const API_URL = 'http://localhost:8080/api/posts';
export default function usePosts() {
const [posts, setPosts] = useState([]);
@@ -9,36 +9,67 @@ export default function usePosts() {
const fetchPosts = async () => {
try {
const res = await axios.get(API_URL);
setPosts(res.data.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)));
//сортируем по дате создания
const sortedPosts = res.data.sort((a, b) =>
new Date(b.createdAt) - new Date(a.createdAt)
);
setPosts(sortedPosts);
} catch (error) {
console.error('Ошибка при загрузке постов:', error);
}
};
const createPost = async (post) => {
await axios.post(API_URL, post);
fetchPosts();
const createPost = async (postData) => {
try {
const postToSend = {
text: postData.text,
image: postData.imagePreview || '',
group: 'Моя группа'
};
await axios.post(API_URL, postToSend);
await fetchPosts();
} catch (error) {
console.error('Ошибка при создании поста:', error);
throw error;
}
};
const updatePost = async (id, data) => {
await axios.put(`${API_URL}/${id}`, data);
fetchPosts();
const updatePost = async (id, postData) => {
try {
const postToSend = {
text: postData.text,
image: postData.image,
group: postData.group,
};
await axios.put(`${API_URL}/${id}`, postToSend);
await fetchPosts();
} catch (error) {
console.error('Ошибка при обновлении поста:', error);
throw error;
}
};
const deletePost = async (id) => {
await axios.delete(`${API_URL}/${id}`);
fetchPosts();
try {
await axios.delete(`${API_URL}/${id}`);
await fetchPosts();
} catch (error) {
console.error('Ошибка при удалении поста:', error);
throw error;
}
};
const likePost = async (id) => {
const post = posts.find(p => p.id === id);
await axios.put(`${API_URL}/${id}`, { ...post, likes: post.likes + 1 });
fetchPosts();
};
useEffect(() => {
fetchPosts();
}, []);
return { posts, createPost, updatePost, deletePost, likePost };
}
return {
posts,
createPost,
updatePost,
deletePost,
refetch: fetchPosts
};
}

View File

@@ -1,5 +1,4 @@
import React, { useState, useEffect } from 'react';
import { PostService } from '../services/PostService';
import { PostForm } from '../components/PostForm';
import { Post } from '../components/Post';
import Header from '../components/Header/Header';
@@ -9,49 +8,41 @@ import Bottombar from '../components/Bottombar/Bottombar';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap-icons/font/bootstrap-icons.css';
import './css/FeedPage.css';
import usePosts from '../hooks/usePosts'; // Импортируем наш хук
const FeedPage = () => {const [posts, setPosts] = useState([]);
const FeedPage = () => {
const { posts, createPost, updatePost, deletePost, likePost, loading } = usePosts();
const [showForm, setShowForm] = useState(false);
const [editingPost, setEditingPost] = useState(null);
useEffect(() => {
const savedPosts = PostService.getPosts();
setPosts(savedPosts || PostService.getInitialPosts());
}, []);
useEffect(() => {
if (posts.length > 0) {
PostService.savePosts(posts);
}
}, [posts]);
const handleShowForm = () => {
setShowForm(true);
setEditingPost(null);
};
const handleSubmit = (formData) => {
const newPost = {
id: editingPost ? editingPost.id : Date.now(),
text: formData.text,
image: formData.image ? URL.createObjectURL(formData.image) : formData.imagePreview,
group: 'Моя группа',
likes: editingPost ? editingPost.likes : 0,
comments: editingPost ? editingPost.comments : 0,
shares: editingPost ? editingPost.shares : 0,
createdAt: editingPost ? editingPost.createdAt : new Date().toISOString()
};
if (editingPost) {
setPosts(posts.map(post => post.id === editingPost.id ? newPost : post));
} else {
setPosts([newPost, ...posts]);
const handleSubmit = async (formData) => {
try {
if (editingPost) {
// Редактирование существующего поста
await updatePost(editingPost.id, {
text: formData.text,
image: formData.imagePreview || '',
group: 'Моя группа',
likes: editingPost.likes,
comments: editingPost.comments,
shares: editingPost.shares
});
} else {
// Создание нового поста
await createPost(formData);
}
setShowForm(false);
setEditingPost(null);
} catch (error) {
console.error('Ошибка при сохранении поста:', error);
alert('Не удалось сохранить пост');
}
setShowForm(false);
setEditingPost(null);
};
const handleEdit = (post) => {
@@ -59,12 +50,44 @@ const FeedPage = () => {const [posts, setPosts] = useState([]);
setShowForm(true);
};
const handleDelete = (postId) => {
const handleDelete = async (postId) => {
if (window.confirm('Вы уверены, что хотите удалить этот пост?')) {
setPosts(posts.filter(post => post.id !== postId));
try {
await deletePost(postId);
} catch (error) {
console.error('Ошибка при удалении поста:', error);
alert('Не удалось удалить пост');
}
}
};
const handleLike = async (postId) => {
try {
await likePost(postId);
} catch (error) {
console.error('Ошибка при лайке поста:', error);
}
};
if (loading) {
return (
<div>
<Header />
<div className="page d-flex justify-content-center mt-3">
<Leftbar />
<div className="content h-100 w-25 m-1 p-2 mb-5 d-flex flex-column justify-content-center align-items-center">
<div className="spinner-border text-danger" role="status">
<span className="visually-hidden">Загрузка...</span>
</div>
<p className="mt-2">Загрузка постов...</p>
</div>
<Rightbar />
</div>
<Bottombar />
</div>
);
}
return (
<div>
<header><Header /></header>
@@ -85,19 +108,30 @@ const FeedPage = () => {const [posts, setPosts] = useState([]);
{showForm && (
<PostForm
onSubmit={handleSubmit}
onCancel={() => setShowForm(false)}
onCancel={() => {
setShowForm(false);
setEditingPost(null);
}}
initialData={editingPost || {}}
/>
)}
{posts.map(post => (
<Post
key={post.id}
post={post}
onEdit={handleEdit}
onDelete={handleDelete}
/>
))}
{posts.length === 0 ? (
<div className="text-center text-muted py-5">
<i className="bi bi-inbox" style={{ fontSize: '3rem' }}></i>
<p className="mt-3">Пока нет постов. Будьте первым!</p>
</div>
) : (
posts.map(post => (
<Post
key={post.id}
post={post}
onEdit={handleEdit}
onDelete={handleDelete}
onLike={handleLike}
/>
))
)}
</div>
<Rightbar />
@@ -110,4 +144,4 @@ const FeedPage = () => {const [posts, setPosts] = useState([]);
);
};
export default FeedPage;
export default FeedPage;

BIN
Отчет_1.docx Normal file

Binary file not shown.