Controller.java.md

package com.fedoubt.controllers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fedoubt.common.message.CustomHttpStatus;
import com.fedoubt.common.message.ResponseUtils;
import com.fedoubt.dtos.CryptoDto;
import com.fedoubt.ex.CustomException;
import com.fedoubt.pojos.EncryptionRequest;
import com.fedoubt.services.CryptoService;
import com.fedoubt.services.EncryptionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/api/v1/crypto")
public class CryptoController {

    private final CryptoService cryptoService;

    private final EncryptionService encryptionService;

    public CryptoController(CryptoService cryptoService , EncryptionService encryptionService){
        this.cryptoService = cryptoService;
        this.encryptionService = encryptionService;
    }

    private final ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping(value = "/encrypt", consumes = {"application/json", "application/octet-stream"})
    public ResponseEntity<?> encrypt(@RequestBody byte[] data) {
        CryptoDto cryptoDto = requestData(data);
        return ResponseEntity.ok(ResponseUtils.success(cryptoService.encrypt(cryptoDto)));
    }

    private CryptoDto requestData(byte[] data){
        try {
            log.info("data:{}",data);
            EncryptionRequest request = objectMapper.readValue(data, EncryptionRequest.class);
            if (request == null || StringUtils.isEmpty(request.getEncryptedKey())
                    || StringUtils.isEmpty(request.getEncryptedData())) {
                // GlobalExceptionHandler 統一返回
                throw new CustomException(CustomHttpStatus.INVALID_REQUEST_DATA);
            }

            String processedData = encryptionService.processEncryptedData(
                    request.getEncryptedKey(),
                    request.getEncryptedData()
            );
            log.info("processedData:{}",processedData);

            CryptoDto cryptoDto = objectMapper.readValue(processedData, CryptoDto.class);
            log.info("cryptoDto:{}",cryptoDto);
            return cryptoDto;
        } catch (JsonProcessingException e) {
            log.error("JSON 解析錯誤: {}", e.getMessage());
            // GlobalExceptionHandler 統一返回
            throw new CustomException(CustomHttpStatus.INVALID_JSON_FORMAT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}