Skip to content

Commit

Permalink
실종자 List 가져오기 api 변경, ai 탐색결과 가져오기 더미 api 생성
Browse files Browse the repository at this point in the history
�Feat : 실종자 List 가져오기 api 변경, ai 탐색결과 가져오기 더미 api 생성
  • Loading branch information
begong313 authored May 4, 2024
2 parents 2a0a922 + e5cdbb8 commit a7f124b
Show file tree
Hide file tree
Showing 9 changed files with 184 additions and 68 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.capstone.server.dto.*;
import com.capstone.server.exception.CustomException;
import com.capstone.server.model.enums.MissingPeopleSortBy;
import com.capstone.server.model.enums.SearchResultSortBy;
import com.capstone.server.model.enums.Status;
import com.capstone.server.model.enums.Step;
import com.capstone.server.response.SuccessResponse;
Expand Down Expand Up @@ -39,59 +40,34 @@ public class MissingPeopleController {
@Autowired
private SmsService smsService;

@GetMapping()
public ResponseEntity<?> getAllMissingPeople(
@GetMapping("")
public ResponseEntity<?> getMissingPeopleList(
// TODO : page 시작을 1로 맞추기 위해 -1 했음. 수정 필요
@RequestParam(required = false, defaultValue = "1", value = "page") int page,
@RequestParam(required = false, defaultValue = "9", value = "size") int pageSize,
@RequestParam(required = false, defaultValue = "createdAt", value = "criteria") String criteria
) {
List<MissingPeopleListResponseDto> missingPeopleListResponseDtos = missingPeopleService.getAllMissingPeople(page - 1, pageSize, MissingPeopleSortBy.fromValue(criteria));
return ResponseEntity.ok().body(new SuccessResponse(missingPeopleListResponseDtos));
}

@GetMapping("/status")
public ResponseEntity<?> getAllMissingPeopleByStatus(
// TODO : page 시작을 1로 맞추기 위해 -1 했음. 수정 필요
@RequestParam(required = false, defaultValue = "1", value = "page") int page,
@RequestParam(required = false, defaultValue = "9", value = "size") int pageSize,
@RequestParam(required = false, defaultValue = "createdAt", value = "criteria") String criteria,
@RequestParam(required = true, value = "status") String status
) {
List<MissingPeopleListResponseDto> missingPeopleListResponseDtos = missingPeopleService.getAllMissingPeopleByStatus(page - 1, pageSize, MissingPeopleSortBy.fromValue(criteria), Status.fromValue(status));
return ResponseEntity.ok().body(new SuccessResponse(missingPeopleListResponseDtos));
}

@GetMapping("/name")
public ResponseEntity<?> getAllMissingPeopleByNameContaining(
// TODO : page 시작을 1로 맞추기 위해 -1 했음. 수정 필요
@RequestParam(required = false, defaultValue = "1", value = "page") int page,
@RequestParam(required = false, defaultValue = "9", value = "size") int pageSize,
@RequestParam(required = false, defaultValue = "createdAt", value = "criteria") String criteria,
@RequestParam(required = true, value = "name") String name
) {
List<MissingPeopleListResponseDto> missingPeopleListResponseDtos = missingPeopleService.getAllMissingPeopleByNameContaining(page - 1, pageSize, MissingPeopleSortBy.fromValue(criteria), name);
return ResponseEntity.ok().body(new SuccessResponse(missingPeopleListResponseDtos));
}

@GetMapping("/name/status")
public ResponseEntity<?> getAllMissingPeopleByNameContainingAndStatus(
// TODO : page 시작을 1로 맞추기 위해 -1 했음. 수정 필요
@RequestParam(required = false, defaultValue = "1", value = "page") int page,
@RequestParam(required = false, defaultValue = "9", value = "size") int pageSize,
@RequestParam(required = false, defaultValue = "50", value = "size") int pageSize,
@RequestParam(required = false, defaultValue = "createdAt", value = "criteria") String criteria,
@RequestParam(required = true, value = "name") String name,
@RequestParam(required = true, value = "status") String status
@RequestParam(required = false, value = "name") String name,
@RequestParam(required = false, value = "status") String status
) {
List<MissingPeopleListResponseDto> missingPeopleListResponseDtos = missingPeopleService.getAllMissingPeopleByNameContainingAndStatus(page - 1, pageSize, MissingPeopleSortBy.fromValue(criteria), name, Status.fromValue(status));
List<MissingPeopleListResponseDto> missingPeopleListResponseDtos;

MissingPeopleSortBy sortBy = MissingPeopleSortBy.fromValue(criteria);
Status statusValue = Status.fromValue(status);
if (name != null && status != null) {
missingPeopleListResponseDtos = missingPeopleService.getAllMissingPeopleByNameContainingAndStatus(page - 1, pageSize, sortBy, name, statusValue);
} else if (name != null) {
missingPeopleListResponseDtos = missingPeopleService.getAllMissingPeopleByNameContaining(page - 1, pageSize, sortBy, name);
} else if (status != null) {
missingPeopleListResponseDtos = missingPeopleService.getAllMissingPeopleByStatus(page - 1, pageSize, sortBy, statusValue);
} else {
missingPeopleListResponseDtos = missingPeopleService.getAllMissingPeople(page - 1, pageSize, sortBy);
}
return ResponseEntity.ok().body(new SuccessResponse(missingPeopleListResponseDtos));
}

// MissingPeople 하나 가져오기
// MissingPeople 디테일정보 가져오기 (실종자 리포트화면에 쓸거)
@GetMapping("/{id}")
public ResponseEntity<?> getMissingPeopleById(@PathVariable Long id) {

//todo : 리스트용이랑 창에띄어줄용 구분해야될듯
MissingPeopleDetailResponseDto missingPeopleDetailResponseDto = missingPeopleService.getMissingPeopleById(id);
return ResponseEntity.ok().body(new SuccessResponse(missingPeopleDetailResponseDto));
}
Expand Down Expand Up @@ -151,10 +127,12 @@ public ResponseEntity<?> uploadProfileImageToS3(
throw new CustomException(ErrorCode.BAD_REQUEST);
}
String imageName = String.format("missingPeopleId=%d/profile/" + image.getOriginalFilename(), id);
//todo 업로드한 주소를 받아서 db에 image경로 업로드
//s3에 이미지 업로드
S3UploadResponseDto s3UploadResponseDto = missingPeopleService.uploadImageToS3(image, imageName, id);
//경로를 받아서 db에 업로드
System.out.println(s3UploadResponseDto.getPath());
System.out.println(s3UploadResponseDto.getUrl());

missingPeopleService.setProfileImagePath(id, s3UploadResponseDto.getUrl());
return ResponseEntity.ok().body(new SuccessResponse(s3UploadResponseDto));
}
Expand Down Expand Up @@ -190,7 +168,37 @@ public ResponseEntity<?> uploadProfileImageToS3(
return ResponseEntity.ok().body(new SuccessResponse(missingPeopleService.uploadImagesToS3(images, imagePath, id, searchHistoryId)));
}

@GetMapping("/{id}/search-result")
public ResponseEntity<?> getSearchResult(
@PathVariable Long id,
@RequestParam(required = false, value = "step") String step,
@RequestParam(required = false, defaultValue = "0", value = "search-id") long searchId,
@RequestParam(required = false, defaultValue = "similarity", value = "criteria") String criteria,
@RequestParam(required = false, defaultValue = "1", value = "page") int page,
@RequestParam(required = false, defaultValue = "5", value = "size") int pageSize
) {
List<SearchResultDto> searchResultDtos = null;
SearchResultSortBy sortBy = SearchResultSortBy.fromValue(criteria);
if (step == null && searchId == 0) {
Map<String, String> map = new HashMap<>();
map.put("RequestParamError",
"At least one of 'step' or 'searchId' must be provided.");
//todo 예외처리
throw new CustomException(ErrorCode.DATA_INTEGRITY_VALIDATION_ERROR, map);
} else if (step != null) {
//해당 step의 가장 최신 검색결과 가져오기
//테스트를 위해 더미로 보내줌
searchResultDtos = missingPeopleService.getSearchResultBySearchId(2, 15, page - 1, pageSize, sortBy);
} else if (searchId != 0) {
//searchId에 해당하는 검색기록 가져오기
//테스트를 위해 더미로 보내줌
searchResultDtos = missingPeopleService.getSearchResultBySearchId(2, 15, page - 1, pageSize, sortBy);
}
return ResponseEntity.ok().body(new SuccessResponse(searchResultDtos));
}

//탐색결과 이미지 가져오기
//만약 이미지페스만 s3에서 받아온다고 하면 쓸 부분이 있을듯.
@GetMapping("/{id}/search-history/{searchHistoryId}/step/{step}")
public ResponseEntity<?> downloadProfileImageFromS3(
@PathVariable Long id,
Expand All @@ -209,6 +217,7 @@ public ResponseEntity<?> changeStep(@Validated @RequestBody StepDto stepDto, @Pa
return ResponseEntity.ok().body(new SuccessResponse(missingPeopleService.changeStatus(stepDto)));
}

//탐색 단계 가져오기
@GetMapping("/{id}/step")
public ResponseEntity<?> getStep(@PathVariable Long id) {
return ResponseEntity.ok().body(new SuccessResponse(missingPeopleService.getStatus(id)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@


import com.capstone.server.model.SearchResultEntity;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Data
Expand All @@ -21,12 +24,28 @@ public class DetectionResultDto {
public static class ImageData {
private String img_path;
private Long cctvId;
@NotNull
private double Similarity;
}

public SearchResultEntity toSearchResultEntity() {
return SearchResultEntity.builder()
.success(true)
.build();
public SearchResultEntity toSearchResultEntity() {
return SearchResultEntity.builder()
.success(true)
.imageUrl(img_path)
.similarity(Similarity)
.time(extractDateTime(img_path))
.build();
}

LocalDateTime extractDateTime(String s) {
String[] temp = s.split("/");
String lastPart = temp[temp.length - 1];
String date = lastPart.split("_")[1];
String[] times = lastPart.split("_")[2].split("-");
String time = times[0] + "-" + times[1] + "-" + times[2];
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss");
return LocalDateTime.parse(date + "_" + time, formatter);
}
}


}
25 changes: 25 additions & 0 deletions server/src/main/java/com/capstone/server/dto/SearchResultDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.capstone.server.dto;

import com.capstone.server.model.SearchResultEntity;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.time.LocalDateTime;

@Data
@AllArgsConstructor
public class SearchResultDto {
private double similarity;
private String imgUrl;
private LocalDateTime time;

public SearchResultDto(SearchResultEntity searchResultEntity) {
this.similarity = searchResultEntity.getSimilarity();
this.imgUrl = searchResultEntity.getImageUrl();
this.time = searchResultEntity.getTime();
}

public static SearchResultDto fromEntity(SearchResultEntity searchResultEntity) {
return new SearchResultDto(searchResultEntity);
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package com.capstone.server.exception;

import java.util.HashMap;
import java.util.Map;

import com.capstone.server.code.ErrorCode;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.HashMap;
import java.util.Map;

@Getter
@RequiredArgsConstructor
@AllArgsConstructor
Expand All @@ -22,12 +21,23 @@ public CustomException(ErrorCode errorCode, Map<String, String> errorDetails) {
this.errorDetails = errorDetails;
}

public CustomException(ErrorCode errorCode, String errorDetailKey, String errorDetailValue) {
this.errorCode = errorCode;
Map<String, String> map = new HashMap<>();
map.put(errorDetailKey, errorDetailValue);
errorDetails = map;
}

public CustomException(ErrorCode errorCode, Exception errorException) {
this.errorCode = errorCode;
this.errorDetails = new HashMap<>();
String[] parts = errorException.getMessage().split(":");
String key = parts[0].trim();
String value = parts[0].trim(); //임의수정했음
String value = parts[0].trim();
if (parts[1] != null) {
value = parts[1].trim();
}

this.errorDetails.put(key, value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,17 @@ public class SearchResultEntity {

private LocalDateTime updatedAt;

private double similarity;
private LocalDateTime time;


@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}


@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.capstone.server.model.enums;

import com.capstone.server.code.ErrorCode;
import com.capstone.server.exception.CustomException;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.Arrays;

@Getter
@AllArgsConstructor
public enum SearchResultSortBy {
SIMILARITY("similarity", "similarity"),
LATEST("latest", "time");
private final String value;
private final String sortBy;

public static SearchResultSortBy fromValue(String value) {
return Arrays.stream(SearchResultSortBy.values())
.filter(sortBy -> sortBy.value.equals(value.trim()))
.findFirst()
.orElseThrow(() -> new CustomException(ErrorCode.BAD_REQUEST, "sort type error", "wrong sort type"));
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
package com.capstone.server.repository;

import com.capstone.server.model.SearchHistoryEntity;
import com.capstone.server.model.SearchResultEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.capstone.server.model.SearchHistoryEntity;
import java.util.List;

public interface SearchResultRepository extends JpaRepository<SearchResultEntity, Long>{
@Repository
public interface SearchResultRepository extends JpaRepository<SearchResultEntity, Long> {
List<SearchResultEntity> findAllBySearchHistoryEntity(SearchHistoryEntity searchHistoryEntity);

Page<SearchResultEntity> findAllBySearchHistoryEntity(Pageable pageable, SearchHistoryEntity searchHistoryEntity);
}
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,11 @@ public void postDetectionResult(DetectionResultDto detectionResultDto) {

//imgaepath한줄씩 database에 업로드
for (DetectionResultDto.ImageData imageData : detectionResultDto.getData()) {
SearchResultEntity searchResult = detectionResultDto.toSearchResultEntity();
SearchResultEntity searchResult = imageData.toSearchResultEntity();
searchResult.setSearchHistoryEntity(searchHistory);

CCTVEntity cctvEntity = cctvRepository.getReferenceById(imageData.getCctvId());
searchResult.setCctvEntity(cctvEntity);
searchResult.setImageUrl(imageData.getImg_path());
searchResultRepository.save(searchResult);
}
} catch (Exception e) {
Expand Down
Loading

0 comments on commit a7f124b

Please sign in to comment.