PublicInfo 추가, 기존 클래스 삭제

master
mjkhan21 10 months ago
parent 23cdf3c4e6
commit 351a9bb73a

@ -1,139 +0,0 @@
package cokr.xit.interfaces.publicinfo;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.core.io.ClassPathResource;
import com.fasterxml.jackson.core.type.TypeReference;
import cokr.xit.foundation.Assert;
import cokr.xit.foundation.data.JSON;
public class Configuration {
private static final LinkedHashMap<String, Configuration> confs;
static {
try {
ClassPathResource res = new ClassPathResource("intf-conf/public-info.conf");
confs = new JSON().parse(res.getInputStream(), new TypeReference<LinkedHashMap<String, Configuration>>() {});
confs.forEach((k, v) -> v.name = k);
} catch (Exception e) {
throw Assert.runtimeException(e);
}
}
public static final Map<String, Configuration> get() {
return confs;
}
public static final Configuration get(String name) {
return Assert.notEmpty(confs.get(name), name);
}
private String
name,
/** 행정정보 공동이용 서비스가 발급한 api key */
apiKey,
/** 서비스 api url */
apiUrl,
/** 이용기관 gpki server id */
userServerId,
/** 보유기관 gpki server id */
providerServerId;
private boolean
/** 데이터 암복호화 사용 여부 */
gpki,
/** 보유기관 가상 데이터 사용 여부 */
mock;
public String getName() {
return name;
}
/** api key .
* @return apiKey
*/
public String getApiKey() {
return apiKey;
}
/** api key .
* @param apiKey apiKey
*/
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
/** api url .
* @return api url
*/
public String getApiUrl() {
return apiUrl;
}
/** api url .
* @param apiUrl api url
*/
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
}
/** gpki server id .
* @return gpki server id
*/
public String getUserServerId() {
return userServerId;
}
/** gpki server id .
* @param userServerId gpki server id
*/
public void setUserServerId(String userServerId) {
this.userServerId = userServerId;
}
/** gpki server id .
* @return gpki server id
*/
public String getProviderServerId() {
return providerServerId;
}
/** gpki server id .
* @param providerServerId gpki server id
*/
public void setProviderServerId(String providerServerId) {
this.providerServerId = providerServerId;
}
/** .
* @return
*/
public boolean isGpki() {
return gpki;
}
/** .
* @param gpki
*/
public void setGpki(boolean gpki) {
this.gpki = gpki;
}
/** .
* @return
*/
public boolean isMock() {
return mock;
}
/** .
* @param mock
*/
public void setMock(boolean mock) {
this.mock = mock;
}
}

@ -0,0 +1,395 @@
package cokr.xit.interfaces.publicinfo;
import java.io.InputStream;
import java.net.http.HttpResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
import org.springframework.core.io.ClassPathResource;
import cokr.xit.foundation.AbstractComponent;
import cokr.xit.foundation.Assert;
import cokr.xit.foundation.data.JSON;
import cokr.xit.foundation.web.WebClient;
import cokr.xit.interfaces.gpki.GPKI;
import lombok.Getter;
import lombok.Setter;
public class PublicInfo extends AbstractComponent {
private static final PublicInfo conf;
static {
try (InputStream input = new ClassPathResource("intf-conf/public-info.conf").getInputStream()) {
conf = new JSON().parse(input, PublicInfo.class);
} catch (Exception e) {
throw runtimeException(e);
}
}
private static final String host() {
return conf.host;
}
private static final String hostIpAddress() {
return conf.hostIp;
}
public static final API api(String name) {
if (isEmpty(conf.apis))
return null;
if (isEmpty(name)) {
API def = conf.apis.get("default");
if (def != null)
return def;
for (API api: conf.apis.values())
return api;
}
return conf.apis.get(name);
}
public static final String describe() {
ArrayList<String> strs = new ArrayList<>();
strs.add("host: " + host());
strs.add("hostIpAddress: " + hostIpAddress());
if (!isEmpty(conf.apis))
conf.apis.values().forEach(api -> {
strs.add("========== API('" + api.name + "') ==========");
for (String str: api.getHeaders().toString().replace("{", "").replace("}", "").split(", "))
strs.add(str);
});
return String.join("\n", strs);
}
private String
host,
hostIp;
private Map<String, API> apis;
public void setHost(String host) {
this.host = host;
hostIp = host.substring(host.lastIndexOf("/") + 1);
}
public void setApis(List<API> apis) {
this.apis = apis.stream().collect(Collectors.toMap(api -> api.name, api -> api));
}
@Getter
@Setter
public static class API {
private static final SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS",Locale.KOREA);
private static String txId() {
return dataFormat.format(new Date()) + key(8);
}
private static String key(int length) {
char[] chars = new char[length];
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < length; i++) {
switch (r.nextInt(3)) {
case 0: chars[i] = (char)(r.nextInt(26) + 65); break;
case 1: chars[i] = (char)(r.nextInt(10) + 48); break;
case 2: chars[i] = (char)(r.nextInt(26) + 97); break;
default: chars[i] = (char)r.nextInt(256);
}
}
return String.valueOf(chars);
}
private String
name,
url,
key,
userServerId,
providerServerId;
private boolean
gpki,
mock;
public String url(String uri) {
return host() + uri;
}
public String url() {
return url(url);
}
public Map<String, String> getHeaders() {
LinkedHashMap<String, String> headers = new LinkedHashMap<>();
headers.put("Host", hostIpAddress());
headers.put("Accept", "application/json");
headers.put("User-Agent", "java-net-httpclient");
headers.put("SOAPAction", "");
headers.put("api_key", key);
headers.put("tx_id", txId());
headers.put("cert_server_id", userServerId);
headers.put("gpki_yn", gpki ? "Y" : "N");
headers.put("mock_yn", mock ? "Y" : "N");
return headers;
}
}
/**
* @author mjkhan
*/
public static class Request {
private String uri;
private LinkedHashMap<String, String> headers;
private List<Object> data;
public String uri() {
return uri;
}
public Request setUri(String uri) {
this.uri = uri;
return this;
}
public Map<String, String> headers() {
return ifEmpty(headers, Collections::emptyMap);
}
public Request header(String name, String value) {
if (headers == null)
headers = new LinkedHashMap<>();
headers.put(name, value);
return this;
}
/**data .
* @return data
*/
public List<Object> getData() {
return ifEmpty(data, () -> data = new ArrayList<>());
}
/**data .
* @param data data
* @return Request
*/
public Request setData(List<Object> data) {
this.data = data;
return this;
}
/** .
* @param objs
* @return Request
*/
public Request addData(Object... objs) {
if (!Assert.isEmpty(objs))
getData().addAll(List.of(objs));
return this;
}
}
/**
* @author mjkhan
*/
public static class Response {
/** 응답코드 */
private int status;
/** 응답헤더 */
private Map<String, List<String>> headers;
/** 응답본문 */
private String body;
/** 에러 */
private Throwable error;
/** .
* @return
*/
public int getStatus() {
return status;
}
/** .
* @param status
* @return Response
*/
public Response setStatus(int status) {
this.status = status;
return this;
}
/** .
* @return
*/
public Map<String, List<String>> getHeaders() {
return headers;
}
public List<String> getHeader(String name) {
List<String> values = headers != null ? headers.get(name) : null;
return values != null ? values : Collections.emptyList();
}
public String header(String name) {
List<String> values = getHeader(name);
return values.isEmpty() ? values.get(0) : "";
}
/** .
* @param headers
* @return Response
*/
public Response setHeaders(Map<String, List<String>> headers) {
this.headers = headers;
return this;
}
/** .
* @return
*/
public String getBody() {
return body;
}
/** .
* @param body
* @return Response
*/
public Response setBody(String body) {
this.body = peel(body);
return this;
}
public boolean success() {
return error == null && status == 200;
}
/** .
* @return
*/
public Throwable getError() {
return error;
}
/** .
* @param error
* @return Response
*/
public Response setError(Throwable error) {
this.error = error;
return this;
}
private static String peel(String str) {
if (isEmpty(str))
return str;
int pos = str.indexOf("[");
if (pos < 0)
return str;
String result = str.substring(pos + 1);
pos = result.lastIndexOf("]");
if (pos < 0)
return str;
return result.substring(0, pos).trim();
}
}
public static class Client {
private JSON json;
private API api;
private GPKI gpki;
public Client setApi(String name) {
api = api(notEmpty(name, "name"));
gpki = api.isGpki() ? new GPKI() : null;
return this;
}
public Client setJSON(JSON json) {
this.json = json;
return this;
}
public Response send(Request req) {
String url = isEmpty(req.uri()) ? api.url() : api.url(req.uri());
Map<String, String> headers = api.getHeaders();
headers.putAll(req.headers());
try {
HttpResponse<String> hresp = new WebClient().post(hreq ->
hreq.uri(url)
.json(json)
.noCache()
.header(headers)
.bodyData(reqBody(req))
);
int statusCode = hresp.statusCode();
String body = hresp.body();
log(Client.class).debug("statusCode: {}", statusCode);
log(Client.class).debug("body:\n{}", body);
return new Response()
.setStatus(statusCode)
.setHeaders(hresp.headers().map())
.setBody(200 == statusCode ? respBody(body) : body);
} catch (Exception e) {
return new Response().setError(rootCause(e));
}
}
private String reqBody(Request req) {
String str = json.stringify(req);
if (gpki != null)
log(Client.class).debug("request body:\n{}", json.stringify(req, true));
return gpki == null ? str : gpki.encrypt(api.getProviderServerId(), str);
}
private String respBody(String str) {
if (gpki == null)
return str;
String body = gpki.decrypt(str);
log(Client.class).debug("decrypted:\n{}", body);
return body;
}
}
@Getter
@Setter
public static class Fault {
private String
code,
loc;
private ErrorMessage message;
}
@Getter
@Setter
public static class ErrorMessage {
static final boolean included(String str) {
return str.contains("errorMessage")
&& str.contains("errorCode");
}
private String
errorMessage,
errorCode;
}
}

@ -1,69 +0,0 @@
package cokr.xit.interfaces.publicinfo;
import java.net.http.HttpResponse;
import cokr.xit.foundation.AbstractComponent;
import cokr.xit.foundation.data.JSON;
import cokr.xit.foundation.web.WebClient;
import cokr.xit.interfaces.gpki.GPKI;
public class ServiceClient extends AbstractComponent {
private JSON json;
private Configuration conf;
private GPKI gpki;
public ServiceClient setConf(String confName) {
conf = Configuration.get(notEmpty(confName, "confName"));
gpki = conf.isGpki() ? new GPKI() : null;
return this;
}
public ServiceClient setJSON(JSON json) {
this.json = json;
return this;
}
public ServiceMessage.Response request(Object... objs) {
if (isEmpty(objs)) return null;
ServiceMessage.Response resp = new ServiceMessage.Response();
try {
HttpResponse<String> hresp = new WebClient().post(req ->
req.uri(conf.getApiUrl())
.json(json)
.header(ServiceMessage.Support.header(conf.getName()))
.bodyData(reqBody(objs))
);
int statusCode = hresp.statusCode();
String body = hresp.body();
log().debug("statusCode: {}", statusCode);
log().debug("body:\n{}", body);
return resp
.setStatus(statusCode)
.setHeaders(hresp.headers().map())
.setBody(200 == statusCode ? respBody(body) : body);
} catch (Exception e) {
return resp.setError(rootCause(e));
}
}
private String reqBody(Object... objs) {
ServiceMessage msg = new ServiceMessage().addData(objs);
String str = json.stringify(msg);
if (gpki != null)
log().debug("request body:\n{}", json.stringify(msg, true));
return gpki == null ? str : gpki.encrypt(conf.getProviderServerId(), str);
}
private String respBody(String str) {
if (gpki == null)
return str;
String body = gpki.decrypt(str);
log().debug("decrypted:\n{}", body);
return body;
}
}

@ -1,187 +0,0 @@
package cokr.xit.interfaces.publicinfo;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import cokr.xit.foundation.Assert;
/**
* @author mjkhan
*/
public class ServiceMessage {
private List<Object> data;
/**data .
* @return data
*/
public List<Object> getData() {
return Assert.ifEmpty(data, () -> data = new ArrayList<>());
}
/**data .
* @param data data
*/
public void setData(List<Object> data) {
this.data = data;
}
/** .
* @param objs
* @return ServiceMessage
*/
public ServiceMessage addData(Object... objs) {
if (!Assert.isEmpty(objs))
getData().addAll(List.of(objs));
return this;
}
/**
* @author mjkhan
*/
public static class Response {
/** 응답코드 */
private int status;
/** 응답헤더 */
private Map<String, List<String>> headers;
/** 응답본문 */
private String body;
/** 에러 */
private Throwable error;
/** .
* @return
*/
public int getStatus() {
return status;
}
/** .
* @param status
* @return Response
*/
public Response setStatus(int status) {
this.status = status;
return this;
}
/** .
* @return
*/
public Map<String, List<String>> getHeaders() {
return headers;
}
public List<String> getHeader(String name) {
List<String> values = headers != null ? headers.get(name) : null;
return values != null ? values : Collections.emptyList();
}
public String header(String name) {
List<String> values = getHeader(name);
return values.isEmpty() ? values.get(0) : "";
}
/** .
* @param headers
* @return Response
*/
public Response setHeaders(Map<String, List<String>> headers) {
this.headers = headers;
return this;
}
/** .
* @return
*/
public String getBody() {
return body;
}
/** .
* @param body
* @return Response
*/
public Response setBody(String body) {
this.body = body;
return this;
}
public boolean success() {
return error == null && status == 200;
}
/** .
* @return
*/
public Throwable getError() {
return error;
}
/** .
* @param error
* @return Response
*/
public Response setError(Throwable error) {
this.error = error;
return this;
}
}
public static class Support {
private static final SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS",Locale.KOREA);
public static final Map<String, String> header(String confName) {
Configuration conf = Configuration.get(confName);
try {
return Map.of(
"api_key", conf.getApiKey(),
"gpki_yn", conf.isGpki() ? "Y" : "N",
"mock_yn", conf.isMock() ? "Y" : "N",
"cert_server_id", conf.getUserServerId(),
"tx_id", txId(),
"SOAPAction", "",
// "Host", InetAddress.getLocalHost().toString(),
"User-Agent", "java-net-httpclient"
);
} catch (Exception e) {
throw Assert.runtimeException(e);
}
}
private static String txId() {
return dataFormat.format(new Date()) + key(8);
}
private static String key(int length) {
char[] chars = new char[length];
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < length; i++) {
switch (r.nextInt(3)) {
case 0: chars[i] = (char)(r.nextInt(26) + 65); break;
case 1: chars[i] = (char)(r.nextInt(10) + 48); break;
case 2: chars[i] = (char)(r.nextInt(26) + 97); break;
default: chars[i] = (char)r.nextInt(256);
}
}
return String.valueOf(chars);
}
public static String peel(String str) {
String prefix = "\"data\": [";
int pos = str.indexOf(prefix);
if (pos < 0) {
prefix = "\"data\":[";
pos = str.indexOf(prefix);
}
String result = str.substring(pos + prefix.length());
return result.substring(0, result.lastIndexOf("]")).trim();
}
}
}

@ -1,12 +1,30 @@
{
"basic-info-ext": { /* 자동차 기본정보(연료 제원 포함) 조회 */
"apiKey": "59f26bf09ed196bfbd98210388c4c6ea9dd0f77bde3f35526f082647a305325b", /* 행정정보 공동이용 서비스가 발급한 api key */
/*"apiUrl": "http://10.188.225.25:29001/piss/api/molit/SignguCarBassMatterInqireService", /* 행정정보 운영 url */
"apiUrl": "http://10.188.225.94:29001/piss/api/molit/SignguCarBassMatterInqireService", /* 행정정보 개발 url */
"userServerId": "SVR1311000030", /* 이용기관 gpki server id */
"providerServerId": "SVR1500000015", /* 보유기관 gpki server id */
"host": "http://10.188.225.94:29001",
/* 행정정보 url
운영: http://10.188.225.25:29001
개발: http://10.188.225.94:29001
*/
"apis": [
{
"name": "lvis",
"gpki": true, /* 데이터 암복호화 사용 여부 */
"mock": false /* 보유기관 가상 데이터 사용 여부 */
}
"userServerId": "SVR1311000030",
"providerServerId": "SVR1500000015",
"gpki": true,
"mock": false
}
]
/* API 설정 템플릿
{
"name": "이용 API 이름",
"url": "API URL",
"key": "행정정보 공동이용 서비스가 발급한 api key",
"userServerId": "이용기관 gpki server id",
"providerServerId": "보유기관 gpki server id",
"gpki": true, // 데이터 암복호화 사용 여부
"mock": false // 보유기관 가상 데이터 사용 여부
}
*/
}

@ -1,121 +1,12 @@
package cokr.xit.interfaces.publicinfo;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import cokr.xit.foundation.data.JSON;
import cokr.xit.foundation.test.TestSupport;
public class ConfigurationTest extends TestSupport {
@Test
void get() {
Map<String, Configuration> confs = Configuration.get();
Assertions.assertNotNull(confs);
confs.keySet().forEach(System.out::println);
Configuration conf = Configuration.get("apiName");
Assertions.assertNotNull(conf);
}
@Test
void header() {
ServiceMessage.Support.header("basic-info-ext")
.forEach((k, v) -> System.out.println(String.format("%s = %s", k, v)));
}
@Test
void body() {
Object1 obj1_0 = new Object1();
obj1_0.setId("1_0");
obj1_0.setName("1 zero");
Object2 obj2_0 = new Object2();
obj2_0.setId("2_0");
obj2_0.setName("2 zero");
obj2_0.setPhoneNo("222-2222");
ServiceMessage msg = new ServiceMessage();
msg.getData().add(obj1_0);
msg.getData().add(obj2_0);
JSON json = new JSON();
String str = json.stringify(msg, true);
System.out.println(str);
Object parsed = json.parse(str, ServiceMessage.class);
System.out.println(parsed);
}
public static class Object1 {
private String id;
private String name;
/**id() .
* @return id
*/
public String getId() {
return id;
}
/**id() .
* @param id id
*/
public void setId(String id) {
this.id = id;
}
/**name() .
* @return name
*/
public String getName() {
return name;
}
/**name() .
* @param name name
*/
public void setName(String name) {
this.name = name;
}
}
public static class Object2 {
private String id;
private String name;
private String phoneNo;
/**id() .
* @return id
*/
public String getId() {
return id;
}
/**id() .
* @param id id
*/
public void setId(String id) {
this.id = id;
}
/**name() .
* @return name
*/
public String getName() {
return name;
}
/**name() .
* @param name name
*/
public void setName(String name) {
this.name = name;
}
/**phoneNo() .
* @return phoneNo
*/
public String getPhoneNo() {
return phoneNo;
}
/**phoneNo() .
* @param phoneNo phoneNo
*/
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
void publicInfo() {
System.out.println(PublicInfo.describe());
}
}
Loading…
Cancel
Save