localhost-back/src/main/java/io/company/localhost/common/dto/MapDto.java
2025-02-20 16:19:52 +09:00

110 lines
3.6 KiB
Java

/************************************************************
*
* @packageName : io.company.localhost.common.dto
* @fileName : MapDto.java
* @author : 조인제
* @date : 24.12.06
* @description :
*
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 24.12.06 조인제 최초 생성
*
*************************************************************/
package io.company.localhost.common.dto;
import org.apache.commons.collections.map.ListOrderedMap;
import org.springframework.util.ObjectUtils;
import java.io.Serial;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MapDto extends ListOrderedMap {
@Serial
private static final long serialVersionUID = -5354101794266218602L;
public MapDto() {
super();
}
public MapDto(Map<String, Object> map) {
super(map);
}
/**
* 주어진 키에 해당하는 값을 String 타입으로 반환합니다.
* 값이 null인 경우, null을 반환합니다.
*
* @param key Map에서 값을 검색할 키
* @return 해당 키에 대한 값(String 타입), 값이 없으면 null
*/
public String getString(String key) {
return (String) get(key); // key에 해당하는 값을 String으로 캐스팅하여 반환
}
/**
* 주어진 키에 해당하는 값을 BigDecimal 타입으로 반환합니다.
* 값이 null이거나 비어있으면 null을 반환합니다.
*
* @param key Map에서 값을 검색할 키
* @return 해당 키에 대한 값(BigDecimal 타입), 값이 없으면 null
*/
public BigDecimal getBigDecimal(String key) {
// key에 해당하는 값을 String으로 가져오고, BigDecimal로 변환하여 반환
return ObjectUtils.isEmpty(get(key)) ? null : new BigDecimal(getString(key));
}
/**
* 주어진 키에 해당하는 값을 Integer 타입으로 반환합니다.
* 값이 BigInteger인 경우 자동으로 int로 변환합니다.
*
* @param key Map에서 값을 검색할 키
* @return 해당 키에 대한 값(Integer 타입), 값이 없으면 null
*/
public Integer getInt(String key) {
Object value = get(key);
if (value instanceof BigInteger) {
return ((BigInteger) value).intValue();
} else if (value instanceof Integer) {
return (Integer) value;
}
return null;
}
public <T> List<T> getList(String key, Class<T> clazz) {
Object value = this.get(key);
if (value == null) {
return Collections.emptyList();
}
if (!(value instanceof List<?>)) {
throw new IllegalArgumentException("Value for key " + key + " is not a List");
}
List<?> list = (List<?>) value;
List<T> result = new ArrayList<>();
for (Object item : list) {
if (item == null) {
continue; // null인 항목은 건너뜁니다.
}
if (clazz.isInstance(item)) {
result.add(clazz.cast(item));
} else if (clazz.equals(Long.class) && item instanceof Integer) {
result.add(clazz.cast(Long.valueOf((Integer) item)));
} else if (item instanceof Map && clazz.equals(MapDto.class)) {
result.add(clazz.cast(new MapDto((Map<String, Object>) item)));
} else {
throw new ClassCastException("Cannot cast " + item.getClass() + " to " + clazz);
}
}
return result;
}
}