본문 바로가기
포트폴리오/Java rest api

rest api filter에서 header, body 변경

by NaHyungMin 2022. 9. 7.

하고 싶은 것 : 1차 필터 완료 후 2차 필터에서 클라이언트에서 제공받은 토큰으로 redis 형식의 데이터를 controller로 던지고 싶음. 매번 controller나 service에서 정보를 체크하기엔 코드량이 늘어남.

package com.program.application.controller;

import com.program.application.entity.main.CustomerEntity;
import com.program.application.model.redis.RedisUserInformation;
import com.program.application.service.main.ICustomerService;
import com.program.commons.response.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/customer", produces = "application/json; charset=UTF-8")
public class CustomerController {

  @Autowired
  @Qualifier("ICustomerMasterServiceImpl")
  private ICustomerService customerService;

  @PostMapping(value = "/list")
  public ResponseResult getCustomerList(@RequestBody(required = false) *** 이부분 *** RedisUserInformation redisUserInformation) {
    return customerService.getCustomerList(redisUserInformation);
  }
}

 

@Order(9999)
@Component
public class AccessTokenFilter extends OncePerRequestFilter {
    @Autowired IRedisUser redisUser;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        HttpHeaders requestHeaders = new HttpHeaders();
        Enumeration headerNames = request.getHeaderNames();

        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            requestHeaders.add(headerName, request.getHeader(headerName));
        }

        //선행 Common Filter에서 처리
        if(!requestHeaders.containsKey("access-token")) {
            filterChain.doFilter(request, response);
        } else {
            String accessToken = request.getHeader(ConstString.AccessToken);
            RedisUserInformation redisUserInformation = redisUser.getRedisUser(accessToken);

            if(CommonUtil.isEmpty(redisUserInformation)) {
                throw new RestapiResultException(ResultCode.UserAuthorizedFailed.getCode(), "정보를 찾을 수 없습니다.");
            }

            //Header 변경 시 사용
            /*RequestWrapper requestWrapper = new RequestWrapper(request);
            requestWrapper.addHeader("header_key", "value");*/

            //Body 추가
            InputStream inputStream = request.getInputStream();
            byte[] rawData = IOUtils.toByteArray(inputStream);
            JsonObject jsonObject;

            if(rawData.length > 0) {
                jsonObject = JsonConverter.readJSONStringFromRequestBody(rawData);
            } else {
                jsonObject = new JsonObject();

                //jsonObject = JsonConverter.readJSONStringFromRequestBody(rawData);
            }

            //Type type = new TypeToken<RedisUserInformation>(){}.getType();
            Type type = new TypeToken<String>(){}.getType();

            //JsonElement jsonElement = JsonConverter.toJsonElement(type, redisUserInformation);
            JsonElement jsonElementUserKey = JsonConverter.toJsonElement(type, redisUserInformation.getUserKey());
            JsonElement jsonElementPartnerCode = JsonConverter.toJsonElement(type, redisUserInformation.getPartnerCode());
            jsonObject.add("userKey", jsonElementUserKey);
            jsonObject.add("partnerCode", jsonElementPartnerCode);

            RequestWrapper requestWrapper = new RequestWrapper(request);
            requestWrapper.newBodyBytes = jsonObject.toString().getBytes(StandardCharsets.UTF_8);

            redisUser.updateRedisUser(accessToken, redisUserInformation);

            filterChain.doFilter(requestWrapper, response);
        }
    }
}

 

package com.program.commons.util;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.gson.*;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class JsonConverter {
  private static final Gson gson = new GsonBuilder()
          .disableHtmlEscaping()
          .setPrettyPrinting()
          .serializeNulls()
          .excludeFieldsWithoutExposeAnnotation()
          .serializeSpecialFloatingPointValues()
          .create();

  private static final JsonParser parser = new JsonParser();

  public static <T extends Map<?, ?>> String convert(T obj) {
    return gson.toJson(obj);
  }

  public static String convert(Object obj){
    return gson.toJson(obj);
  }

  public static <T extends Class<?>, V> String convert(T cls, V obj) {
    return gson.toJson(obj);
  }

  public static <T, V extends String> List<T> convertToClassList(Class<T> cls, V value) {
    return gson.fromJson(value, com.google.gson.reflect.TypeToken.getParameterized(List.class, cls).getType());
  }

  public static <T, V extends String> T convertToClass(Class<T> cls, V value) throws JsonSyntaxException {
    return gson.fromJson(value, (Type)cls);
  }

  public static <T extends Class<?>, V> JsonElement toJsonElement(Type type, V value) {
    JsonElement jsonElement = gson.fromJson(convert(value), JsonElement.class);
    return jsonElement;
  }

  public static <V> JsonElement toJsonElement(V value) {
    String s = convert(value);

    return parser.parse(convert(value));
  }

  public static String toJson(Object object) {
    if (object == null)
      return null;

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    String json = "";
    try {
      json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return json;
  }

  public static JsonObject readJSONStringFromRequestBody(byte[] rawData) {
    StringBuffer json = new StringBuffer();
    ObjectMapper mapper = new ObjectMapper();
    String line = null;
    InputStream is = null;
    try {
      is = new ByteArrayInputStream(rawData);
      BufferedReader reader = new BufferedReader(new InputStreamReader(is));
      while((line = reader.readLine()) != null) {
        json.append(line);
      }

    }catch(Exception e) {
      e.printStackTrace();
      //log.info("Error reading JSON string: " + e.toString());
    }

    System.out.println(json.toString());
    //Map<String, String> map = mapper.readValue(json.toString(), Map.class);

    //JsonObject jsonObject = new JsonObject();

    JsonObject jsonObject = gson.fromJson(convert(json.toString()), JsonObject.class);
    return jsonObject;
  }
}

'포트폴리오 > Java rest api' 카테고리의 다른 글

Reuters 환율 처리  (1) 2022.11.18
중계 서버  (0) 2022.11.18
rest api + jpa(jpql) + replica set  (0) 2022.08.02
자바 날씨 API  (0) 2021.06.09
Java 기본 Rest api  (0) 2020.08.11