fix: ADDS-API 호출 적용

dev
Jonguk. Lim 5 months ago
parent 9cae629cd6
commit b0e968a84d

@ -0,0 +1,127 @@
package cokr.xit.adds.cmm.model;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonRootName;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* <pre>
* description :
*
* packageName : kr.xit.core.model
* fileName : ApiBaseResponse
* author : limju
* date : 2024-03-15
* ======================================================================
*
* ----------------------------------------------------------------------
* 2024-03-15 limju
*
* </pre>
*/
@Data
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Builder
@JsonRootName("result")
//@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiBaseResponse<T> {
/**
* -
*/
private Integer code = ResultCode.SUCCESS.getStatusCode();
/**
* -
*/
private String message = ResultCode.SUCCESS.getMessage();
/**
*
*/
private T data;
/**
*
*/
private int totalCount;
/**
* API or
*/
private Boolean success = Objects.equals(code, ResultCode.SUCCESS.getStatusCode());
/**
* API
*/
@Builder.Default
private String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// public static <T> ApiBaseResponse<T> of() {
// return new ApiBaseResponse<>();
// }
//
// public static <T> ApiBaseResponse<T> of(T data) {
// return new ApiBaseResponse<>(data);
// }
//
// public static <T> ApiBaseResponse<T> empty() {
// return new ApiBaseResponse<>(null, ResultCode.NO_CONTENT);
// }
//
// private ApiBaseResponse(T data) {
//
// if(ObjectUtils.isEmpty(data)) {
// this.code = ResultCode.NO_CONTENT.getStatusCode();
// this.message = ResultCode.NO_CONTENT.getMessage();
// this.data = null;
// }else{
// this.code = ResultCode.SUCCESS.getStatusCode();
// this.message = ResultCode.findByStatusCode(code).getMessage();
// this.data = data;
// }
// }
//
// private ApiBaseResponse(T data, ResultCode resultCode) {
// this.success = true;
// this.code = resultCode.getStatusCode();
// this.message = resultCode.getMessage();
// this.data = null;
// }
//
// public ApiBaseResponse(Integer code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public ApiBaseResponse(Integer code, String message, T data) {
// this.code = code;
// this.message = message;
// this.data = data;
// }
public int getTotalCount() {
if(data == null){
this.totalCount = 0;
}else {
if (Collection.class.isAssignableFrom(data.getClass())) {
this.totalCount = ((Collection<?>) data).size();
} else {
this.totalCount = 1;
}
}
return totalCount;
}
}

@ -0,0 +1,236 @@
// package cokr.xit.adds.cmm.model;
//
// import java.io.FileInputStream;
// import java.io.IOException;
// import java.io.StringReader;
// import java.net.http.HttpResponse;
// import java.time.LocalDate;
// import java.time.format.DateTimeFormatter;
// import java.time.format.DateTimeParseException;
// import java.util.List;
// import java.util.Set;
//
// import javax.validation.ConstraintViolation;
// import javax.validation.Validator;
// import javax.xml.XMLConstants;
// import javax.xml.transform.stream.StreamSource;
// import javax.xml.validation.Schema;
// import javax.xml.validation.SchemaFactory;
//
// import org.apache.commons.lang3.ObjectUtils;
// import org.apache.commons.lang3.StringUtils;
// import org.json.simple.JSONObject;
// import org.springframework.http.HttpHeaders;
// import org.xml.sax.SAXException;
//
// import com.fasterxml.jackson.core.type.TypeReference;
//
// import cokr.xit.adds.core.spring.exception.ApiCustomException;
// import cokr.xit.foundation.data.JSON;
// import cokr.xit.foundation.web.WebClient;
//
// /**
// * <pre>
// * description :
// *
// * author : limju
// * date : 2024-04-04
// * ======================================================================
// * 변경일 변경자 변경 내용
// * ----------------------------------------------------------------------
// * 2024-04-04 limju 최초 생성
// *
// * </pre>
// */
// public class ApiUtil {
//
// /**
// * 유효성 검증
// * errList가 null인 경우 유효성 검증 실패 시 예외 throw ApiCustomException
// *
// * @param t validatable object
// * @param errList error list
// * @param validator validator
// */
// public static <T> void validate(final T t, final List<String> errList, final Validator validator) {
// final Set<ConstraintViolation<T>> list = validator.validate(t);
//
// if(!list.isEmpty()) {
// final List<String> errors = list.stream()
// .map(row -> String.format("%s=%s", row.getPropertyPath(), row.getMessageTemplate()))
// .toList();
//
// // 추가적인 유효성 검증이 필요 없는 경우
// if(errList == null){
// if(!errors.isEmpty()) throw ApiCustomException.create(errors.toString());
// return;
// }
// errList.addAll(errors);
// }
// }
//
// public static void checkYmdError(String dt, String fieldName) {
// String msg = "유효한 일자가 아닙니다.";
// if(ObjectUtils.isEmpty(fieldName)){
// msg = "ymd=" + msg;
// }else{
// msg = fieldName + "=" + msg;
// }
// try {
// final LocalDate rdt = LocalDate.parse(dt, DateTimeFormatter.ofPattern("yyyyMMdd"));
// if(!dt.equals(DateTimeFormatter.ofPattern("yyyyMMdd").format(rdt))){
// throw ApiCustomException.create(msg);
// }
// } catch (DateTimeParseException e) {
// throw ApiCustomException.create(msg);
// }
// }
//
// public static void checkDatetimeError(String dt, String fieldName) {
// String msg = "유효한 일시가 아닙니다.";
// if(ObjectUtils.isEmpty(fieldName)){
// msg = "ymd=" + msg;
// }else{
// msg = fieldName + "=" + msg;
// }
// try {
// final LocalDate rdt = LocalDate.parse(dt, DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
// if(!dt.equals(DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(rdt))){
// throw ApiCustomException.create(msg);
// }
// } catch (DateTimeParseException e) {
// throw ApiCustomException.create(msg);
// }
// }
//
// /**
// * NimsApi 호출 - x-www-form-urlencoded 방식
// * @param uri String
// * @param cls T
// * @return String
// */
// public static <T> String callNimsApi(String uri, T cls) {
// HttpResponse<String> rslt = new WebClient().post(request -> {
// request.contentType(WebClient.Request.ContentType.FORM);
// request.uri(uri);
// toData(request, cls);
// });
// return rslt.body();
// }
//
// /**
// * irosApi 호출 - x-www-form-urlencoded 방식
// * @param uri String
// * @param param String
// * @return String
// */
// public static String callIrosApi(String uri, String param) {
// HttpResponse<String> rslt = new WebClient().get(request -> {
// request.header(HttpHeaders.CONTENT_TYPE, "application/json");
// request.contentType(WebClient.Request.ContentType.FORM);
// request.uri(uri + param);
// });
// return rslt.body();
// }
//
// /**
// * Object -> data로 변환
// * @param request WebClient.Request
// * @param obj Object
// */
// public static void toData(final WebClient.Request request, final Object obj){
// if(ObjectUtils.isEmpty(obj)) return;
//
// JSONObject jsonObj = toObjByObj(obj, JSONObject.class);
// for (Object key : jsonObj.keySet()) {
// // API 호출 시 필요없는 파라메터 제외
// if("userId".equals(key) || "dbSkipYn".equals(key)) continue;
// request.data((String) key, ObjectUtils.isEmpty(jsonObj.get(key))? StringUtils.EMPTY: jsonObj.get(key));
// }
// }
//
// /**
// * Object -> class로 변환
// * @param obj Object
// * @param cls Class
// * @return T
// */
// public static <T> T toObjByObj(final Object obj, final Class<T> cls) {
// try {
// return ObjectUtils.isNotEmpty(obj)? new JSON().getObjectMapper().convertValue(obj, cls) : null;
// } catch (IllegalArgumentException e) {
// throw ApiCustomException.create(e.getLocalizedMessage());
// }
// }
//
// /**
// * Object -> TypeReference로 변환
// * @param obj Object
// * @param typeRef TypeReference
// * @return T
// */
// public static <T> T toObjByObj(final Object obj, final TypeReference<T> typeRef) {
// try {
// return ObjectUtils.isNotEmpty(obj)? new JSON().getObjectMapper().convertValue(obj, typeRef) : null;
// } catch (IllegalArgumentException e) {
// throw ApiCustomException.create(e.getLocalizedMessage());
// }
// }
//
// /**
// * XML 유효성 검증
// * @param xmlStr String
// * @param xsdFilePathName String
// * @return boolean
// */
// public static boolean validateXml(final String xmlStr, final String xsdFilePathName) {
// try {
// FileInputStream fis = new FileInputStream(xsdFilePathName);
// SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// Schema schema = sf.newSchema(new StreamSource(fis));
//
// javax.xml.validation.Validator validator = schema.newValidator();
// validator.validate(new StreamSource(new StringReader(xmlStr)));
// return true;
//
// } catch (SAXException | IOException e) {
// throw ApiCustomException.create(e.getMessage());
// }
// }
//
// /**
// * XML 유효성 검증
// * @param xmlStr String
// * @param xsdFilePath String
// * @return boolean
// */
// public static boolean validateXmlFromXmlStr(final String xmlStr, final String xsdFilePath) {
// try {
// FileInputStream fis = new FileInputStream(xsdFilePath);
// SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// Schema schema = sf.newSchema(new StreamSource(fis));
//
// javax.xml.validation.Validator validator = schema.newValidator();
// validator.validate(new StreamSource(new StringReader(xmlStr)));
// return true;
//
// } catch (SAXException | IOException e) {
// throw ApiCustomException.create(e.getMessage());
// }
// }
//
// /**
// * XML 유효성 검증
// * @param xmlFilePath String
// * @param xsdFilePath String
// * @return boolean
// */
// public static boolean validateXmlFromFile(String xmlFilePath, final String xsdFilePath) {
// try (FileInputStream fileInputStream = new FileInputStream(xmlFilePath)) {
// byte[] bytes = fileInputStream.readAllBytes();
// return validateXmlFromXmlStr(new String(bytes), xsdFilePath);
// }catch (IOException e) {
// throw ApiCustomException.create(e.getMessage());
// }
// }
// }

@ -0,0 +1,46 @@
package cokr.xit.adds.cmm.model;
import java.util.Arrays;
import org.springframework.http.HttpStatus;
import lombok.Getter;
@Getter
public enum ResultCode {
// 2xx
SUCCESS(HttpStatus.OK.value(), "성공"), // 200
NO_CONTENT(HttpStatus.NO_CONTENT.value(), "데이터가 없습니다"), // 204
// 4xx
BAD_REQUEST(HttpStatus.BAD_REQUEST.value(), "항목이 올바르지 않습니다"), // 400
INVALID_DATA(HttpStatus.BAD_REQUEST.value(), "데이터 처리 오류 발생"), // 400
LOGIN_ERROR(HttpStatus.BAD_REQUEST.value(), "아이디 혹은 비밀번호를 다시 확인하세요."), // 400
INVALID_PARAMETER(HttpStatus.BAD_REQUEST.value(), "필수 파라미터가 누락되었습니다"), // 500
UNAUTHORIZED(HttpStatus.UNAUTHORIZED.value(), "인증이 필요합니다"), // 401
FORBIDDEN(HttpStatus.FORBIDDEN.value(), "권한이 없습니다"), // 403
TOKEN_EXPIRED(HttpStatus.FORBIDDEN.value(), "토큰이 만료되었습니다"), // 403
INVALID_ACCESS_TOKEN(HttpStatus.FORBIDDEN.value(), "토큰이 유효하지 않습니다"), // 403
NOT_FOUND(HttpStatus.NOT_FOUND.value(), "요청한 api를 찾을 수 없습니다."), // 404
// 5xx
INVALID_JSON(HttpStatus.INTERNAL_SERVER_ERROR.value(), "전달된 JSON 형식이 올바르지 않습니다"), // 500
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR.value(), "서버 에러가 발생했습니다"), // 500
;
private final Integer statusCode;
private final String message;
ResultCode(Integer statusCode, String message){
this.statusCode = statusCode;
this.message = message;
}
public static ResultCode findByStatusCode(int statusCode){
return Arrays.stream(ResultCode.values())
.filter(ssc -> ssc.getStatusCode() == statusCode)
.findFirst()
.orElse(INVALID_DATA);
}
}

@ -1,34 +1,27 @@
package cokr.xit.adds.nims.web; package cokr.xit.adds.nims.web;
import java.util.Collection;
import java.util.function.Consumer;
import java.net.http.HttpResponse; import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Consumer;
import javax.annotation.Resource;
import javax.json.JsonObject;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject; import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import net.minidev.json.parser.ParseException; import net.minidev.json.parser.ParseException;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.type.TypeReference;
import cokr.xit.adds.nims.service.DsuseMgtReceiptService; import cokr.xit.adds.cmm.model.ApiBaseResponse;
import cokr.xit.adds.nims.BsshQuery;
import cokr.xit.adds.nims.ProductQuery; import cokr.xit.adds.nims.ProductQuery;
import cokr.xit.foundation.data.DataObject;
import cokr.xit.foundation.data.JSON;
import cokr.xit.foundation.web.AbstractController; import cokr.xit.foundation.web.AbstractController;
import cokr.xit.foundation.web.WebClient; import cokr.xit.foundation.web.WebClient;
import cokr.xit.foundation.web.WebClient.Request.ContentType;
import cokr.xit.foundation.web.WebClient.Request; import cokr.xit.foundation.web.WebClient.Request;
import cokr.xit.foundation.data.DataObject; import cokr.xit.foundation.web.WebClient.Request.ContentType;
@ -40,6 +33,7 @@ import cokr.xit.foundation.data.DataObject;
public class ProductController extends AbstractController { public class ProductController extends AbstractController {
public static final String CLASS_URL = "/adds/nims"; public static final String CLASS_URL = "/adds/nims";
JSON json = new JSON();
public class METHOD_URL { public class METHOD_URL {
public static final String public static final String
@ -76,53 +70,48 @@ public class ProductController extends AbstractController {
String sMethod = "POST"; String sMethod = "POST";
DataObject dataObject = new DataObject(); DataObject dataObject = new DataObject();
dataObject.put("k",""); //dataObject.put("k","");
dataObject.put("fg","1"); dataObject.put("fg","1");
dataObject.put("pg","1"); dataObject.put("pg","1");
dataObject.put("ymd",""); dataObject.put("ymd","");
dataObject.put("fg2",""); dataObject.put("fg2","");
dataObject.put("p",query.getSchProductCd()); //query.setSchProductCd("8806578045922");
dataObject.put("pn",query.getSchProductNm()); if(!isEmpty(query.getSchProductCd())) dataObject.put("p",query.getSchProductCd());
if(!isEmpty(query.getSchProductNm())) dataObject.put("pn",query.getSchProductNm());
dataObject.put("dbSkipYn","N"); dataObject.put("dbSkipYn","N");
dataObject.put("userId","suji"); dataObject.put("userId","suji");
ObjectMapper mapper = new ObjectMapper();
String sJsonData = mapper.writeValueAsString(dataObject);
Consumer<Request> configurer = (request) -> { Consumer<Request> configurer = (request) -> {
request.uri("http://localhost:9076/api/biz/nims/v1/getNimsProductInfoKd") request.uri("http://localhost:9076/api/biz/nims/v1/getNimsProductInfoKd")
.contentType(ContentType.JSON) .contentType(ContentType.JSON)
.bodyData(sJsonData); .bodyData(json.stringify(dataObject));
}; };
HttpResponse<String> hresp = null; HttpResponse<String> hresp = null;
if(sMethod.equals("POST")) { if(sMethod.equals("POST")) {
hresp = new WebClient() hresp = new WebClient()
.post(configurer); .post(configurer);
} else if(sMethod.equals("GET")) { } else if(sMethod.equals("GET")) {
hresp = new WebClient() hresp = new WebClient()
.get(configurer); .get(configurer);
} }
String resBody = hresp.body(); String resBody = hresp.body();
ApiBaseResponse<List<JSONObject>> jsonData = json.parse(resBody, new TypeReference<>() {});
System.out.println(resBody);
JSONParser parser = new JSONParser();
Object obj = parser.parse( resBody ); // ApiBaseResponse(code=400, message=상품번호 또는 상품명은 필수 입니다, data=null, totalCount=0, success=false, responseTime=2024-06-12 15:35:24)
JSONObject jsonObj = (JSONObject) obj; if(!jsonData.getSuccess()){
JSONArray jsonData = (JSONArray) jsonObj.get("data"); // error 처리
// throw new Exception(data.getMessage());
}
List<JSONObject> data = jsonData.getData();
System.out.println(resBody);
System.out.println(jsonData.get(0).toString());
ModelAndView result = new ModelAndView("jsonView"); ModelAndView result = new ModelAndView("jsonView");
result.addObject("productMainList", data);
result.addObject("productMainList", jsonData) // 발송 정보
;
return result; return result;
} }
} }

@ -94,6 +94,7 @@
$P.control = new DatasetControl({ $P.control = new DatasetControl({
urls : { urls : {
load : wctx.url("/adds/nims/product-list.do") load : wctx.url("/adds/nims/product-list.do")
//load : '<c:url value="http://localhost:9076/api/biz/nims/v1/getProductInfoByQrcodeImg" />',
} }
, prefix: "productMain" , prefix: "productMain"
, prefixName: "마약류 제품 조회" , prefixName: "마약류 제품 조회"

Loading…
Cancel
Save