forked from mtusi2026/mtusi2026lab2
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a724337538 |
@@ -30,3 +30,10 @@ coverage/
|
|||||||
.vscode/
|
.vscode/
|
||||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||||
|
.gradle/
|
||||||
|
**/ .gradle/
|
||||||
|
**/build/
|
||||||
|
*.iml.gradle/
|
||||||
|
build/
|
||||||
|
**/build/
|
||||||
|
.env
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
build.gradle.kts
|
|
||||||
.gradle
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
package org.example.config;
|
|
||||||
|
|
||||||
import jakarta.validation.Constraint;
|
|
||||||
import jakarta.validation.Payload;
|
|
||||||
|
|
||||||
import java.lang.annotation.*;
|
|
||||||
|
|
||||||
@Documented
|
|
||||||
@Constraint(validatedBy = CodePointSizeValidator.class)
|
|
||||||
@Target({ ElementType.FIELD, ElementType.PARAMETER })
|
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
|
||||||
public @interface CodePointSize {
|
|
||||||
int min() default 0;
|
|
||||||
int max() default Integer.MAX_VALUE;
|
|
||||||
String message() default "size must be between {min} and {max} code points";
|
|
||||||
Class<?>[] groups() default {};
|
|
||||||
Class<? extends Payload>[] payload() default {};
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package org.example.config;
|
|
||||||
|
|
||||||
import jakarta.validation.ConstraintValidator;
|
|
||||||
import jakarta.validation.ConstraintValidatorContext;
|
|
||||||
|
|
||||||
public class CodePointSizeValidator implements ConstraintValidator<CodePointSize, String> {
|
|
||||||
|
|
||||||
private int min;
|
|
||||||
private int max;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void initialize(CodePointSize annotation) {
|
|
||||||
this.min = annotation.min();
|
|
||||||
this.max = annotation.max();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean isValid(String value, ConstraintValidatorContext context) {
|
|
||||||
if (value == null) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
int n = value.codePointCount(0, value.length());
|
|
||||||
return n >= min && n <= max;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,38 +5,11 @@ import org.springframework.context.annotation.Configuration;
|
|||||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
|
||||||
import java.security.MessageDigest;
|
|
||||||
import java.security.NoSuchAlgorithmException;
|
|
||||||
import java.util.HexFormat;
|
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
public class PasswordConfig {
|
public class PasswordConfig {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
public PasswordEncoder passwordEncoder() {
|
public PasswordEncoder passwordEncoder() {
|
||||||
BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder();
|
return new BCryptPasswordEncoder();
|
||||||
|
|
||||||
return new PasswordEncoder() {
|
|
||||||
private String prehash(String raw) {
|
|
||||||
try {
|
|
||||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
|
||||||
byte[] digest = md.digest(raw.getBytes(StandardCharsets.UTF_8));
|
|
||||||
return HexFormat.of().formatHex(digest);
|
|
||||||
} catch (NoSuchAlgorithmException e) {
|
|
||||||
throw new IllegalStateException(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String encode(CharSequence rawPassword) {
|
|
||||||
return bcrypt.encode(prehash(rawPassword.toString()));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean matches(CharSequence rawPassword, String encodedPassword) {
|
|
||||||
return bcrypt.matches(prehash(rawPassword.toString()), encodedPassword);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
package org.example.config;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.core.JsonParser;
|
|
||||||
import com.fasterxml.jackson.core.JsonToken;
|
|
||||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
|
||||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
|
|
||||||
public class StrictStringDeserializer extends JsonDeserializer<String> {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
|
||||||
if (p.currentToken() != JsonToken.VALUE_STRING) {
|
|
||||||
return (String) ctxt.handleUnexpectedToken(String.class, p);
|
|
||||||
}
|
|
||||||
return p.getValueAsString();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package org.example.controller;
|
package org.example.controller;
|
||||||
|
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import jakarta.validation.constraints.Max;
|
|
||||||
import jakarta.validation.constraints.Min;
|
import jakarta.validation.constraints.Min;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.example.dto.ChatPage;
|
import org.example.dto.ChatPage;
|
||||||
@@ -42,7 +41,6 @@ public class ChatController {
|
|||||||
@GetMapping
|
@GetMapping
|
||||||
public ChatPage getChats(
|
public ChatPage getChats(
|
||||||
@RequestParam(defaultValue = "50")
|
@RequestParam(defaultValue = "50")
|
||||||
@Max(100)
|
|
||||||
@Min(value = 1, message = "limit must be >= 1") int limit
|
@Min(value = 1, message = "limit must be >= 1") int limit
|
||||||
) {
|
) {
|
||||||
return chatService.getChatsForCurrentUser(limit);
|
return chatService.getChatsForCurrentUser(limit);
|
||||||
@@ -84,7 +82,6 @@ public class ChatController {
|
|||||||
@PathVariable("id") UUID id,
|
@PathVariable("id") UUID id,
|
||||||
@RequestParam(required = false) String cursor,
|
@RequestParam(required = false) String cursor,
|
||||||
@RequestParam(defaultValue = "50")
|
@RequestParam(defaultValue = "50")
|
||||||
@Max(100)
|
|
||||||
@Min(value = 1, message = "limit must be >= 1") int limit
|
@Min(value = 1, message = "limit must be >= 1") int limit
|
||||||
) {
|
) {
|
||||||
UUID userId = userService.getCurrentUser().getId();
|
UUID userId = userService.getCurrentUser().getId();
|
||||||
|
|||||||
@@ -1,23 +1,18 @@
|
|||||||
package org.example.dto.create;
|
package org.example.dto.create;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
|
||||||
import jakarta.validation.constraints.NotBlank;
|
import jakarta.validation.constraints.NotBlank;
|
||||||
import jakarta.validation.constraints.NotEmpty;
|
import jakarta.validation.constraints.NotEmpty;
|
||||||
import jakarta.validation.constraints.NotNull;
|
import jakarta.validation.constraints.NotNull;
|
||||||
import jakarta.validation.constraints.Size;
|
import jakarta.validation.constraints.Size;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import org.example.config.CodePointSize;
|
|
||||||
import org.example.config.StrictStringDeserializer;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class CreateChatDto {
|
public class CreateChatDto {
|
||||||
@NotBlank(message = "Title не может быть пустым")
|
@NotBlank(message = "Title не может быть пустым")
|
||||||
@CodePointSize(min = 1, max = 100)
|
@Size(max = 100, message = "Title не должен превышать 32 символов")
|
||||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
|
||||||
private String title;
|
private String title;
|
||||||
|
|
||||||
@JsonProperty("member_ids")
|
@JsonProperty("member_ids")
|
||||||
|
|||||||
@@ -1,16 +1,12 @@
|
|||||||
package org.example.dto.create;
|
package org.example.dto.create;
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
|
||||||
import jakarta.validation.constraints.NotBlank;
|
import jakarta.validation.constraints.NotBlank;
|
||||||
import jakarta.validation.constraints.Size;
|
import jakarta.validation.constraints.Size;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import org.example.config.CodePointSize;
|
|
||||||
import org.example.config.StrictStringDeserializer;
|
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class CreateMessageDto {
|
public class CreateMessageDto {
|
||||||
@NotBlank(message = "Текст сообщения не может быть пустым")
|
@NotBlank(message = "Текст сообщения не может быть пустым")
|
||||||
@CodePointSize(min = 1, max = 4000)
|
@Size(max = 4000, message = "Максимальная длина сообщения — 1024 символов")
|
||||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
|
||||||
private String text;
|
private String text;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,26 @@
|
|||||||
package org.example.dto.create;
|
package org.example.dto.create;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
|
||||||
import jakarta.validation.constraints.NotBlank;
|
import jakarta.validation.constraints.NotBlank;
|
||||||
import jakarta.validation.constraints.Pattern;
|
import jakarta.validation.constraints.Pattern;
|
||||||
import jakarta.validation.constraints.Size;
|
import jakarta.validation.constraints.Size;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import org.example.config.CodePointSize;
|
|
||||||
import org.example.config.StrictStringDeserializer;
|
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class CreateUserDto {
|
public class CreateUserDto {
|
||||||
@NotBlank
|
@NotBlank(message = "Username не может быть пустым")
|
||||||
@Size(min = 3, max = 32)
|
@Size(max = 64, message = "Username не должен превышать 64 символов")
|
||||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
@JsonProperty("username")
|
||||||
@Pattern(regexp = "^[a-z0-9_]{3,32}$")
|
@Pattern(regexp = "^[a-z0-9_]{3,32}$")
|
||||||
private String username;
|
private String username;
|
||||||
|
|
||||||
@NotBlank(message = "Display name не может быть пустым")
|
@NotBlank(message = "Display name не может быть пустым")
|
||||||
@CodePointSize(min = 1, max = 128)
|
@Size(max = 100, message = "Display name не должен быть больше 128 символов")
|
||||||
@JsonProperty("display_name")
|
@JsonProperty("display_name")
|
||||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
|
||||||
private String displayName;
|
private String displayName;
|
||||||
|
|
||||||
@NotBlank(message = "Password не может быть пустым")
|
@NotBlank(message = "Password не может быть пустым")
|
||||||
@CodePointSize(min = 12, max = 128)
|
@Size(min = 12, max = 128, message = "Password: 12–128 символа")
|
||||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
|
||||||
private String password;
|
private String password;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,12 @@
|
|||||||
package org.example.dto.update;
|
package org.example.dto.update;
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
|
||||||
import jakarta.validation.constraints.NotBlank;
|
import jakarta.validation.constraints.NotBlank;
|
||||||
import jakarta.validation.constraints.Size;
|
import jakarta.validation.constraints.Size;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import org.example.config.CodePointSize;
|
|
||||||
import org.example.config.StrictStringDeserializer;
|
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class UpdateChatDto {
|
public class UpdateChatDto {
|
||||||
@NotBlank
|
@NotBlank
|
||||||
@CodePointSize(min = 1, max = 100)
|
@Size(max = 32)
|
||||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
|
||||||
private String title;
|
private String title;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,12 @@
|
|||||||
package org.example.dto.update;
|
package org.example.dto.update;
|
||||||
|
|
||||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
|
||||||
import jakarta.validation.constraints.NotBlank;
|
import jakarta.validation.constraints.NotBlank;
|
||||||
import jakarta.validation.constraints.Size;
|
import jakarta.validation.constraints.Size;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import org.example.config.CodePointSize;
|
|
||||||
import org.example.config.StrictStringDeserializer;
|
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class UpdateMessageDto {
|
public class UpdateMessageDto {
|
||||||
@NotBlank
|
@NotBlank
|
||||||
@CodePointSize(min = 1, max = 4000)
|
@Size(max = 1024)
|
||||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
|
||||||
private String text;
|
private String text;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,14 @@
|
|||||||
package org.example.dto.update;
|
package org.example.dto.update;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
|
||||||
import jakarta.validation.constraints.NotBlank;
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Size;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import org.example.config.CodePointSize;
|
|
||||||
import org.example.config.StrictStringDeserializer;
|
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public class UpdateUserDto {
|
public class UpdateUserDto {
|
||||||
@NotBlank
|
@NotBlank
|
||||||
@CodePointSize(min = 1, max = 128)
|
@Size(max = 128)
|
||||||
@JsonProperty("display_name")
|
@JsonProperty("display_name")
|
||||||
@JsonDeserialize(using = StrictStringDeserializer.class)
|
|
||||||
private String displayName;
|
private String displayName;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import org.springframework.http.converter.HttpMessageNotReadableException;
|
|||||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
|
||||||
|
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
@@ -185,24 +184,4 @@ public class GlobalExceptionHandler {
|
|||||||
.header("X-Request-Id", reqId)
|
.header("X-Request-Id", reqId)
|
||||||
.body(body);
|
.body(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
|
||||||
public ResponseEntity<?> handleTypeMismatch(
|
|
||||||
MethodArgumentTypeMismatchException ex,
|
|
||||||
HttpServletRequest request
|
|
||||||
) {
|
|
||||||
String reqId = resolveRequestId(request);
|
|
||||||
String message = "Invalid parameter";
|
|
||||||
if (ex.getRequiredType() == UUID.class) {
|
|
||||||
message = "Invalid UUID";
|
|
||||||
}
|
|
||||||
ErrorResponse body = new ErrorResponse(
|
|
||||||
new ErrorDetail("Invalid parameter", "Invalid UUID", reqId)
|
|
||||||
);
|
|
||||||
// Error body: code invalid_request, request_id = reqId
|
|
||||||
return ResponseEntity
|
|
||||||
.status(HttpStatus.BAD_REQUEST)
|
|
||||||
.header("X-Request-Id", reqId)
|
|
||||||
.body(body);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -29,7 +29,7 @@ public class Chat {
|
|||||||
@GeneratedValue(strategy = GenerationType.UUID)
|
@GeneratedValue(strategy = GenerationType.UUID)
|
||||||
private UUID id;
|
private UUID id;
|
||||||
|
|
||||||
@Column(nullable = false, length = 100)
|
@Column(nullable = false, length = 32)
|
||||||
private String title;
|
private String title;
|
||||||
|
|
||||||
@OneToMany(mappedBy = "chat", fetch = FetchType.LAZY)
|
@OneToMany(mappedBy = "chat", fetch = FetchType.LAZY)
|
||||||
|
|||||||
@@ -1,23 +1,10 @@
|
|||||||
package org.example.repository;
|
package org.example.repository;
|
||||||
|
|
||||||
import org.example.model.Chat;
|
import org.example.model.Chat;
|
||||||
import org.springframework.data.domain.Pageable;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.Query;
|
|
||||||
import org.springframework.data.repository.query.Param;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
public interface ChatRepository extends JpaRepository<Chat, UUID> {
|
public interface ChatRepository extends JpaRepository<Chat, UUID> {
|
||||||
@Query("""
|
|
||||||
SELECT c FROM Chat c
|
|
||||||
JOIN ChatMember m ON m.chatId = c.id
|
|
||||||
WHERE m.userId = :userId
|
|
||||||
ORDER BY c.createdAt ASC, c.id ASC
|
|
||||||
""")
|
|
||||||
List<Chat> findForUserOrderByCreatedAtAsc(
|
|
||||||
@Param("userId") UUID userId,
|
|
||||||
Pageable pageable);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,22 +6,20 @@ import org.springframework.data.jpa.repository.Query;
|
|||||||
import org.springframework.data.repository.query.Param;
|
import org.springframework.data.repository.query.Param;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
|
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
public interface MessageRepository extends JpaRepository<Message, UUID> {
|
public interface MessageRepository extends JpaRepository<Message, UUID> {
|
||||||
|
List<Message> findByChatIdOrderByCreatedAtDescIdDesc(UUID chatId, Pageable pageable);
|
||||||
List<Message> findByChatIdOrderByCreatedAtAscIdAsc(UUID chatId, Pageable pageable);
|
|
||||||
|
|
||||||
@Query("""
|
@Query("""
|
||||||
SELECT m FROM Message m
|
SELECT m FROM Message m
|
||||||
WHERE m.chatId = :chatId
|
WHERE m.chatId = :chatId
|
||||||
AND (m.createdAt > :createdAt
|
AND (m.createdAt < :createdAt
|
||||||
OR (m.createdAt = :createdAt AND m.id > :id))
|
OR (m.createdAt = :createdAt AND m.id < :id))
|
||||||
ORDER BY m.createdAt ASC, m.id ASC
|
ORDER BY m.createdAt DESC, m.id DESC
|
||||||
""")
|
""")
|
||||||
List<Message> findNextPage(
|
List<Message> findNextPage(
|
||||||
@Param("chatId") UUID chatId,
|
@Param("chatId") UUID chatId,
|
||||||
@@ -29,6 +27,5 @@ public interface MessageRepository extends JpaRepository<Message, UUID> {
|
|||||||
@Param("id") UUID id,
|
@Param("id") UUID id,
|
||||||
Pageable pageable
|
Pageable pageable
|
||||||
);
|
);
|
||||||
|
|
||||||
Optional<Message> findByIdAndChatId(UUID id, UUID chatId);
|
Optional<Message> findByIdAndChatId(UUID id, UUID chatId);
|
||||||
}
|
}
|
||||||
@@ -107,40 +107,25 @@ public class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private final ConcurrentHashMap<String, Object> inflight = new ConcurrentHashMap<>();
|
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
|
||||||
public Optional<User> resolveUserByBearer(String rawToken) {
|
public Optional<User> resolveUserByBearer(String rawToken) {
|
||||||
if (rawToken == null || rawToken.isBlank()) {
|
String hash = TokenHasher.sha256(rawToken);
|
||||||
return Optional.empty();
|
|
||||||
|
Optional<UUID> cached = cacheService.get(hash);
|
||||||
|
if (cached.isPresent()) {
|
||||||
|
return userRepository.findById(cached.get());
|
||||||
}
|
}
|
||||||
|
|
||||||
final String hash = TokenHasher.sha256(rawToken);
|
Object lock = locks.computeIfAbsent(hash, h -> new Object());
|
||||||
|
|
||||||
Optional<UUID> cachedUserId = cacheService.get(hash);
|
|
||||||
if (cachedUserId.isPresent()) {
|
|
||||||
return userRepository.findById(cachedUserId.get());
|
|
||||||
}
|
|
||||||
|
|
||||||
Object lock = inflight.computeIfAbsent(hash, h -> new Object());
|
|
||||||
try {
|
try {
|
||||||
synchronized (lock) {
|
synchronized (lock) {
|
||||||
cachedUserId = cacheService.get(hash);
|
cached = cacheService.get(hash);
|
||||||
if (cachedUserId.isPresent()) {
|
if (cached.isPresent()) {
|
||||||
return userRepository.findById(cachedUserId.get());
|
return userRepository.findById(cached.get());
|
||||||
}
|
}
|
||||||
|
return resolveUserByBearer(hash);
|
||||||
Instant now = Instant.now();
|
|
||||||
Optional<Session> session = sessionRepository.findByToken(hash);
|
|
||||||
if (session.isEmpty() || !session.get().isActive(now)) {
|
|
||||||
return Optional.empty();
|
|
||||||
}
|
|
||||||
Session s = session.get();
|
|
||||||
cacheService.put(hash, s.getUserId(), s.getExpiresAt());
|
|
||||||
return userRepository.findById(s.getUserId());
|
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
inflight.remove(hash, lock);
|
locks.remove(hash, lock);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import org.example.model.ChatMember;
|
|||||||
import org.example.model.User;
|
import org.example.model.User;
|
||||||
import org.example.repository.ChatMemberRepository;
|
import org.example.repository.ChatMemberRepository;
|
||||||
import org.example.repository.ChatRepository;
|
import org.example.repository.ChatRepository;
|
||||||
import org.springframework.data.domain.PageRequest;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -32,21 +31,18 @@ public class ChatService {
|
|||||||
User currentUser = userService.getCurrentUser();
|
User currentUser = userService.getCurrentUser();
|
||||||
UUID currentId = currentUser.getId();
|
UUID currentId = currentUser.getId();
|
||||||
|
|
||||||
List<UUID> memberIds = dto.getMemberIds();
|
List<UUID> memberIds = dto.getMemberIds().stream()
|
||||||
if (memberIds == null || memberIds.isEmpty()) {
|
.distinct()
|
||||||
throw new IllegalArgumentException("member_ids must not be empty");
|
.toList();
|
||||||
}
|
|
||||||
long distinctCount = memberIds.stream().distinct().count();
|
|
||||||
if (distinctCount != memberIds.size()) {
|
|
||||||
throw new IllegalArgumentException("duplicate member_ids");
|
|
||||||
}
|
|
||||||
if (!memberIds.contains(currentId)) {
|
if (!memberIds.contains(currentId)) {
|
||||||
throw new IllegalArgumentException(
|
throw new IllegalArgumentException(
|
||||||
"creator must be in member_ids");
|
"Создатель чата должен входить в список участников (member_ids)");
|
||||||
}
|
}
|
||||||
|
|
||||||
for (UUID memberId : memberIds) {
|
for (UUID memberId : memberIds) {
|
||||||
if (!userService.exists(memberId)) {
|
if (!userService.exists(memberId)) {
|
||||||
throw new IllegalArgumentException("unknown member_id");
|
throw new NotFoundException("Пользователь с ID " + memberId + " не найден");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,25 +77,17 @@ public class ChatService {
|
|||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public ChatPage getChatsForCurrentUser(int limit) {
|
public ChatPage getChatsForCurrentUser(int limit) {
|
||||||
if (limit < 1 || limit > 100) {
|
|
||||||
throw new IllegalArgumentException("limit must be 1..100");
|
|
||||||
}
|
|
||||||
UUID userId = userService.getCurrentUser().getId();
|
UUID userId = userService.getCurrentUser().getId();
|
||||||
List<Chat> raw = chatRepository.findForUserOrderByCreatedAtAsc(
|
List<ChatResponse> items = new ArrayList<>();
|
||||||
userId,
|
|
||||||
PageRequest.of(0, limit + 1)
|
|
||||||
);
|
|
||||||
boolean hasMore = raw.size() > limit;
|
|
||||||
List<Chat> page = hasMore ? raw.subList(0, limit) : raw;
|
|
||||||
List<ChatResponse> items = page.stream()
|
|
||||||
.map(c -> toResponse(c.getId()))
|
|
||||||
.toList();
|
|
||||||
String nextCursor = null;
|
|
||||||
if (hasMore && !items.isEmpty()) {
|
|
||||||
nextCursor = items.get(items.size() - 1).getId().toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
return new ChatPage(items, nextCursor);
|
for (ChatMember membership : chatMemberRepository.findByUserId(userId)) {
|
||||||
|
if (items.size() >= limit) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
chatRepository.findById(membership.getChatId())
|
||||||
|
.ifPresent(chat -> items.add(toResponse(chat.getId())));
|
||||||
|
}
|
||||||
|
return new ChatPage(items, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
|
|||||||
@@ -44,8 +44,8 @@ public class MessageService {
|
|||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public MessagePage getMessage(UUID chatId, UUID userId, String cursor, int limit) {
|
public MessagePage getMessage(UUID chatId, UUID userId, String cursor, int limit) {
|
||||||
if (limit < 1 || limit > 100) {
|
if (limit < 1) {
|
||||||
throw new IllegalArgumentException("limit must be between 1 and 100");
|
throw new IllegalArgumentException("Лимит должен быть больше 0");
|
||||||
}
|
}
|
||||||
|
|
||||||
chatService.requireMember(chatId);
|
chatService.requireMember(chatId);
|
||||||
@@ -57,7 +57,7 @@ public class MessageService {
|
|||||||
List<Message> items;
|
List<Message> items;
|
||||||
|
|
||||||
if (cursor == null || cursor.isBlank()) {
|
if (cursor == null || cursor.isBlank()) {
|
||||||
items = messageRepository.findByChatIdOrderByCreatedAtAscIdAsc(chatId, pageable);
|
items = messageRepository.findByChatIdOrderByCreatedAtDescIdDesc(chatId, pageable);
|
||||||
} else {
|
} else {
|
||||||
UUID cursorId;
|
UUID cursorId;
|
||||||
try {
|
try {
|
||||||
@@ -67,7 +67,11 @@ public class MessageService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Message cursorMsg = messageRepository.findByIdAndChatId(cursorId, chatId)
|
Message cursorMsg = messageRepository.findByIdAndChatId(cursorId, chatId)
|
||||||
.orElseThrow(() -> new IllegalArgumentException("Invalid cursor"));
|
.orElse(null);
|
||||||
|
|
||||||
|
if (cursorMsg == null) {
|
||||||
|
throw new IllegalArgumentException("Invalid cursor");
|
||||||
|
}
|
||||||
|
|
||||||
items = messageRepository.findNextPage(
|
items = messageRepository.findNextPage(
|
||||||
chatId,
|
chatId,
|
||||||
@@ -79,18 +83,7 @@ public class MessageService {
|
|||||||
|
|
||||||
String nextCursor = null;
|
String nextCursor = null;
|
||||||
if (items.size() == limit && !items.isEmpty()) {
|
if (items.size() == limit && !items.isEmpty()) {
|
||||||
Message last = items.get(items.size() - 1);
|
nextCursor = items.get(items.size() - 1).getId().toString();
|
||||||
boolean hasMore = !messageRepository
|
|
||||||
.findNextPage(
|
|
||||||
chatId,
|
|
||||||
last.getCreatedAt(),
|
|
||||||
last.getId(),
|
|
||||||
PageRequest.of(0, 1)
|
|
||||||
)
|
|
||||||
.isEmpty();
|
|
||||||
if (hasMore) {
|
|
||||||
nextCursor = last.getId().toString();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return new MessagePage(items, nextCursor);
|
return new MessagePage(items, nextCursor);
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import lombok.RequiredArgsConstructor;
|
|||||||
import org.example.config.UserContext;
|
import org.example.config.UserContext;
|
||||||
import org.example.dto.create.CreateUserDto;
|
import org.example.dto.create.CreateUserDto;
|
||||||
import org.example.dto.update.UpdateUserDto;
|
import org.example.dto.update.UpdateUserDto;
|
||||||
import org.example.exception.ForbiddenException;
|
|
||||||
import org.example.exception.NotFoundException;
|
import org.example.exception.NotFoundException;
|
||||||
import org.example.exception.UnauthorizedException;
|
import org.example.exception.UnauthorizedException;
|
||||||
import org.example.exception.UserAlreadyExistsException;
|
import org.example.exception.UserAlreadyExistsException;
|
||||||
@@ -51,51 +50,32 @@ public class UserService {
|
|||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
|
|
||||||
private User requireCurrentUser() {
|
|
||||||
User user = UserContext.getCurrentUser();
|
|
||||||
if (user == null) {
|
|
||||||
throw new UnauthorizedException("Unauthorized");
|
|
||||||
}
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public User getUserById(UUID id) {
|
public User getUserById(UUID id) {
|
||||||
requireCurrentUser();
|
|
||||||
return userRepository.findById(id)
|
return userRepository.findById(id)
|
||||||
.orElseThrow(() -> new NotFoundException("Пользователь не найден"));
|
.orElseThrow(() -> new NotFoundException("Пользователь с id: " + id + " не найден."));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public User updateUser(UUID id, UpdateUserDto dto) {
|
public User updateUser(UUID id, UpdateUserDto updateObject){
|
||||||
User me = requireCurrentUser();
|
User existing = getUserById(id);
|
||||||
if (!me.getId().equals(id)) {
|
existing.setDisplayName(updateObject.getDisplayName());
|
||||||
throw new ForbiddenException("Forbidden");
|
return userRepository.save(existing);
|
||||||
}
|
}
|
||||||
User user = userRepository.findById(id)
|
|
||||||
.orElseThrow(() -> new NotFoundException("Пользователь не найден"));
|
|
||||||
user.setDisplayName(dto.getDisplayName());
|
|
||||||
return userRepository.save(user);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void deleteUser(UUID id) {
|
|
||||||
User me = requireCurrentUser();
|
|
||||||
if (!me.getId().equals(id)) {
|
|
||||||
throw new ForbiddenException("Forbidden");
|
|
||||||
}
|
|
||||||
if (!userRepository.existsById(id)) {
|
|
||||||
throw new NotFoundException("Пользователь не найден");
|
|
||||||
}
|
|
||||||
userRepository.deleteById(id);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public User updateUser(String id, UpdateUserDto updateObject) {
|
public User updateUser(String id, UpdateUserDto updateObject) {
|
||||||
return updateUser(parseUuid(id), updateObject);
|
return updateUser(parseUuid(id), updateObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional
|
||||||
|
public void deleteUser(UUID id) {
|
||||||
|
if (!userRepository.existsById(id)) {
|
||||||
|
throw new NotFoundException("Пользователь с id: " + id + " не найден");
|
||||||
|
}
|
||||||
|
userRepository.deleteById(id);
|
||||||
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public void deleteUser(String id) {
|
public void deleteUser(String id) {
|
||||||
deleteUser(parseUuid(id));
|
deleteUser(parseUuid(id));
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
spring:
|
spring:
|
||||||
jackson:
|
jackson:
|
||||||
property-naming-strategy: SNAKE_CASE
|
property-naming-strategy: SNAKE_CASE
|
||||||
deserialization:
|
|
||||||
fail-on-unknown-properties: true
|
|
||||||
lifecycle:
|
lifecycle:
|
||||||
timeout-per-shutdown-cycle=10s:
|
timeout-per-shutdown-cycle=10s:
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
DROP INDEX IF EXISTS idx_messages_chat_created_id;
|
|
||||||
|
|
||||||
CREATE INDEX idx_messages_chat_created_id
|
|
||||||
ON messages (chat_id, created_at ASC, id ASC);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
ALTER TABLE chats
|
|
||||||
ALTER COLUMN title TYPE VARCHAR(100);
|
|
||||||
@@ -1,123 +1,123 @@
|
|||||||
//package org.example;
|
package org.example;
|
||||||
//
|
|
||||||
//import org.junit.jupiter.api.DisplayName;
|
import org.junit.jupiter.api.DisplayName;
|
||||||
//import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
//import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
//import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||||
//import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
//import org.springframework.http.MediaType;
|
import org.springframework.http.MediaType;
|
||||||
//import org.springframework.test.web.servlet.MockMvc;
|
import org.springframework.test.web.servlet.MockMvc;
|
||||||
//
|
|
||||||
//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
//import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||||
//import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
//
|
|
||||||
//@SpringBootTest
|
@SpringBootTest
|
||||||
//@AutoConfigureMockMvc
|
@AutoConfigureMockMvc
|
||||||
//public class ApiIntegrationTest {
|
public class ApiIntegrationTest {
|
||||||
//
|
|
||||||
// @Autowired
|
@Autowired
|
||||||
// private MockMvc mockMvc;
|
private MockMvc mockMvc;
|
||||||
// @Test
|
@Test
|
||||||
// @DisplayName("400 1. Неверный / битый JSON должен возвращать 400 Bad Request")
|
@DisplayName("400 1. Неверный / битый JSON должен возвращать 400 Bad Request")
|
||||||
// void shouldReturn400ForMalformedJson() throws Exception {
|
void shouldReturn400ForMalformedJson() throws Exception {
|
||||||
// String malformedJson = "{\"username\": \"bad_json\", \"display_name\":}";
|
String malformedJson = "{\"username\": \"bad_json\", \"display_name\":}";
|
||||||
//
|
|
||||||
// mockMvc.perform(post("/api/v1/users")
|
mockMvc.perform(post("/api/v1/users")
|
||||||
// .contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
// .content(malformedJson))
|
.content(malformedJson))
|
||||||
// .andExpect(status().isBadRequest());
|
.andExpect(status().isBadRequest());
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// @Test
|
@Test
|
||||||
// @DisplayName("400 2. Валидация: пустой username должен возвращать 400 Bad Request")
|
@DisplayName("400 2. Валидация: пустой username должен возвращать 400 Bad Request")
|
||||||
// void shouldReturn400ForEmptyUsername() throws Exception {
|
void shouldReturn400ForEmptyUsername() throws Exception {
|
||||||
// String invalidJson = "{\"username\": \"\", \"display_name\": \"User\"}";
|
String invalidJson = "{\"username\": \"\", \"display_name\": \"User\"}";
|
||||||
//
|
|
||||||
// mockMvc.perform(post("/api/v1/users")
|
mockMvc.perform(post("/api/v1/users")
|
||||||
// .contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
// .content(invalidJson))
|
.content(invalidJson))
|
||||||
// .andExpect(status().isBadRequest());
|
.andExpect(status().isBadRequest());
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// @Test
|
@Test
|
||||||
// @DisplayName("404 3. Неучастник чата получает 404 (чат скрыт)")
|
@DisplayName("404 3. Неучастник чата получает 404 (чат скрыт)")
|
||||||
// void shouldReturn404WhenUserIsNotChatMember() throws Exception {
|
void shouldReturn404WhenUserIsNotChatMember() throws Exception {
|
||||||
// String aliceJson = mockMvc.perform(post("/api/v1/users")
|
String aliceJson = mockMvc.perform(post("/api/v1/users")
|
||||||
// .contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
// .content("{\"username\": \"alice_test\", \"display_name\": \"Alice\"}"))
|
.content("{\"username\": \"alice_test\", \"display_name\": \"Alice\"}"))
|
||||||
// .andExpect(status().isCreated())
|
.andExpect(status().isCreated())
|
||||||
// .andReturn().getResponse().getContentAsString();
|
.andReturn().getResponse().getContentAsString();
|
||||||
// String aliceId = extractId(aliceJson);
|
String aliceId = extractId(aliceJson);
|
||||||
//
|
|
||||||
// String bobJson = mockMvc.perform(post("/api/v1/users")
|
String bobJson = mockMvc.perform(post("/api/v1/users")
|
||||||
// .contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
// .content("{\"username\": \"bob_test\", \"display_name\": \"Bob\"}"))
|
.content("{\"username\": \"bob_test\", \"display_name\": \"Bob\"}"))
|
||||||
// .andExpect(status().isCreated())
|
.andExpect(status().isCreated())
|
||||||
// .andReturn().getResponse().getContentAsString();
|
.andReturn().getResponse().getContentAsString();
|
||||||
// String bobId = extractId(bobJson);
|
String bobId = extractId(bobJson);
|
||||||
//
|
|
||||||
// String spyJson = mockMvc.perform(post("/api/v1/users")
|
String spyJson = mockMvc.perform(post("/api/v1/users")
|
||||||
// .contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
// .content("{\"username\": \"spy_test\", \"display_name\": \"Spy\"}"))
|
.content("{\"username\": \"spy_test\", \"display_name\": \"Spy\"}"))
|
||||||
// .andExpect(status().isCreated())
|
.andExpect(status().isCreated())
|
||||||
// .andReturn().getResponse().getContentAsString();
|
.andReturn().getResponse().getContentAsString();
|
||||||
// String spyId = extractId(spyJson);
|
String spyId = extractId(spyJson);
|
||||||
//
|
|
||||||
// String chatJson = String.format(
|
String chatJson = String.format(
|
||||||
// "{\"title\":\"Private\", \"member_ids\":[\"%s\",\"%s\"]}", aliceId, bobId);
|
"{\"title\":\"Private\", \"member_ids\":[\"%s\",\"%s\"]}", aliceId, bobId);
|
||||||
//
|
|
||||||
// String chat = mockMvc.perform(post("/api/v1/chats")
|
String chat = mockMvc.perform(post("/api/v1/chats")
|
||||||
// .header("X-User-Id", aliceId) // ← обязательно!
|
.header("X-User-Id", aliceId) // ← обязательно!
|
||||||
// .contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
// .content(chatJson))
|
.content(chatJson))
|
||||||
// .andExpect(status().isCreated())
|
.andExpect(status().isCreated())
|
||||||
// .andReturn().getResponse().getContentAsString();
|
.andReturn().getResponse().getContentAsString();
|
||||||
// String chatId = extractId(chat);
|
String chatId = extractId(chat);
|
||||||
//
|
|
||||||
// mockMvc.perform(post("/api/v1/chats/" + chatId + "/messages")
|
mockMvc.perform(post("/api/v1/chats/" + chatId + "/messages")
|
||||||
// .header("X-User-Id", spyId)
|
.header("X-User-Id", spyId)
|
||||||
// .contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
// .content("{\"text\": \"Secret message\"}"))
|
.content("{\"text\": \"Secret message\"}"))
|
||||||
// .andExpect(status().isNotFound());
|
.andExpect(status().isNotFound());
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// @Test
|
@Test
|
||||||
// @DisplayName("200 4. Пагинация: получение ограниченного числа сообщений по limit")
|
@DisplayName("200 4. Пагинация: получение ограниченного числа сообщений по limit")
|
||||||
// void shouldPaginateMessagesWithLimit() throws Exception {
|
void shouldPaginateMessagesWithLimit() throws Exception {
|
||||||
// String userJson = mockMvc.perform(post("/api/v1/users")
|
String userJson = mockMvc.perform(post("/api/v1/users")
|
||||||
// .contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
// .content("{\"username\": \"paginator\", \"display_name\": \"Paginator\"}"))
|
.content("{\"username\": \"paginator\", \"display_name\": \"Paginator\"}"))
|
||||||
// .andExpect(status().isCreated())
|
.andExpect(status().isCreated())
|
||||||
// .andReturn().getResponse().getContentAsString();
|
.andReturn().getResponse().getContentAsString();
|
||||||
// String userId = extractId(userJson);
|
String userId = extractId(userJson);
|
||||||
//
|
|
||||||
// String chat = mockMvc.perform(post("/api/v1/chats")
|
String chat = mockMvc.perform(post("/api/v1/chats")
|
||||||
// .header("X-User-Id", userId)
|
.header("X-User-Id", userId)
|
||||||
// .contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
// .content(String.format(
|
.content(String.format(
|
||||||
// "{\"title\":\"Paginated Chat\", \"member_ids\":[\"%s\"]}", userId)))
|
"{\"title\":\"Paginated Chat\", \"member_ids\":[\"%s\"]}", userId)))
|
||||||
// .andExpect(status().isCreated())
|
.andExpect(status().isCreated())
|
||||||
// .andReturn().getResponse().getContentAsString();
|
.andReturn().getResponse().getContentAsString();
|
||||||
// String chatId = extractId(chat);
|
String chatId = extractId(chat);
|
||||||
//
|
|
||||||
// for (int i = 1; i <= 3; i++) {
|
for (int i = 1; i <= 3; i++) {
|
||||||
// mockMvc.perform(post("/api/v1/chats/" + chatId + "/messages")
|
mockMvc.perform(post("/api/v1/chats/" + chatId + "/messages")
|
||||||
// .header("X-User-Id", userId)
|
.header("X-User-Id", userId)
|
||||||
// .contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
// .content("{\"text\": \"Msg " + i + "\"}"))
|
.content("{\"text\": \"Msg " + i + "\"}"))
|
||||||
// .andExpect(status().isCreated());
|
.andExpect(status().isCreated());
|
||||||
// }
|
}
|
||||||
// mockMvc.perform(get("/api/v1/chats/" + chatId + "/messages")
|
mockMvc.perform(get("/api/v1/chats/" + chatId + "/messages")
|
||||||
// .param("limit", "2")
|
.param("limit", "2")
|
||||||
// .header("X-User-Id", userId))
|
.header("X-User-Id", userId))
|
||||||
// .andExpect(status().isOk())
|
.andExpect(status().isOk())
|
||||||
// .andExpect(jsonPath("$.items.length()").value(2))
|
.andExpect(jsonPath("$.items.length()").value(2))
|
||||||
// .andExpect(jsonPath("$.next_cursor").isNotEmpty());
|
.andExpect(jsonPath("$.next_cursor").isNotEmpty());
|
||||||
// }
|
}
|
||||||
//
|
|
||||||
// private String extractId(String json) {
|
private String extractId(String json) {
|
||||||
// return json.split("\"id\":\"")[1].split("\"")[0];
|
return json.split("\"id\":\"")[1].split("\"")[0];
|
||||||
// }
|
}
|
||||||
//}
|
}
|
||||||
@@ -1,2 +1,3 @@
|
|||||||
# Only for full OpenAPI/JSON Schema validation; HTTP tests use stdlib.
|
# Only for full OpenAPI/JSON Schema validation; HTTP tests use stdlib.
|
||||||
openapi-spec-validator==0.7.2
|
openapi-spec-validator==0.7.2
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
set -eu
|
|
||||||
# TODO: copy to restart.sh and implement using YOUR compose/stack services.
|
|
||||||
# Restart API and ALL used state stores (DB, sessions, S3, broker as applicable).
|
|
||||||
# Preserve persistent volumes and schema/data; never down -v / flush / re-seed.
|
|
||||||
# Allow operator unseal if required in lab7; do not print credentials.
|
|
||||||
# Exit 0 only after the intended action; test waits for API readiness separately.
|
|
||||||
printf '%s
|
|
||||||
' 'TODO: implement restart.sh for your infrastructure' >&2
|
|
||||||
exit 2
|
|
||||||
Reference in New Issue
Block a user