Добавить src/main/java/org/lanit/controllers/JSONController.java

This commit is contained in:
Шимченко 2025-09-12 05:43:20 +00:00
parent 0bd4a82fa2
commit 387551bd7b

View File

@ -0,0 +1,73 @@
package org.lanit.controllers;
import org.lanit.models.*;
import org.lanit.service.JsonProcessingService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.time.Instant;
@RestController
public class JSONController {
private final JsonProcessingService processingService;
private final ObjectMapper objectMapper;
public JSONController(JsonProcessingService processingService, ObjectMapper objectMapper) {
this.processingService = processingService;
this.objectMapper = objectMapper;
}
@GetMapping("/json")
public ResponseEntity<?> handleJsonRequest(
@RequestParam("action") String action,
@RequestBody String jsonBody) throws IOException {
System.out.println("Received JSON: " + jsonBody);
System.out.println("Action: " + action);
try {
if ("add".equals(action)) {
AddRequest addRequest = objectMapper.readValue(jsonBody, AddRequest.class);
Info modifiedInfo = processingService.processAdd(addRequest);
Response response = new Response();
response.setInfo(modifiedInfo);
response.setUuid(addRequest.getUuid());
response.setLastUpdate(Instant.now().toString());
return ResponseEntity.ok(response);
} else if ("delete".equals(action)) {
DeleteRequest deleteRequest = objectMapper.readValue(jsonBody, DeleteRequest.class);
Info modifiedInfo = processingService.processDelete(deleteRequest);
Response response = new Response();
response.setInfo(modifiedInfo);
response.setUuid(deleteRequest.getUuid());
response.setLastUpdate(Instant.now().toString());
return ResponseEntity.ok(response);
} else {
ErrorResponse error = new ErrorResponse();
error.setStatus("error");
error.setMessage("Передан некорректный action - " + action);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
}
} catch (RuntimeException e) {
ErrorResponse error = new ErrorResponse();
error.setStatus("error");
error.setMessage(e.getMessage());
HttpStatus status = e.getMessage().contains("тикер") || e.getMessage().contains("индекс")
? HttpStatus.NOT_FOUND : HttpStatus.BAD_REQUEST;
return ResponseEntity.status(status).body(error);
} catch (IOException e) {
ErrorResponse error = new ErrorResponse();
error.setStatus("error");
error.setMessage("Ошибка разбора JSON");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
}
}
}