서로 다른 유형의 object 복사

 /**
  * @description
  * <pre>
  * source 중 target과 항목명이 같은 데이터를 복사.
  * </pre>
  * @param source 원본 data
  * @param target 타겟 data
  */
  public static void copyData(Object source, Object target) {   
    try {
      BeanUtils.copyProperties(source, target);
    } catch (BeansException be) {
      logger.debug(be.getMessage(), be);
    } catch (Exception e) {
      logger.debug(e.getMessage(), e);
    }
  }

사용예)
  SrcVo src = svc.getData(param);
  TrgtVo trgt = new TrgtVo();
  ErpUtils.copyData(src, trgt);

관련글 : 서로 다른 유형의 List 복사

문자열을 목록으로

문자열 -> 목록
SELECT UNNEST(STRING_TO_ARRAY(‘aa,bb,cc,cc,dd’,’,’))

목록 -> 문자열
SELECT ARRAY_TO_STRING(ARRAY_AGG(col),’,’)
FROM generate_series(1,10) AS col

Multi Session 연결시 TransactionSynchronizationManager 사용하기

1.각각 다른 datasource를 생성한다.
2.Spring Config에서
@EnableTransactionManagement 또는 @EnableAspectJAutoProxy를 사용.
@EnableAspectJAutoProxy 일 경우 transactionManager라는 transaction manager가 설정되어야 한다.
3.TransactionSynchronizationManager 를 사용한다.

설정 : SpringAppConfig.java

@Configuration
@ImportResource({“classpath:/config/spring/.xml”})
@EnableTransactionManagement
public class SpringAppConfig {
}

사용 : WizDao.java

@Repository
 public class WizDao {
  @Autowired
  @Qualifier("masterSqlSession")
  private SqlSession masterSqlSession;

  @Autowired
  @Qualifier("slaveSqlSession")
  private SqlSession slaveSqlSession;
  ...
  private SqlSession getSession() {
    boolean txReadOnly = 
    TransactionSynchronizationManager.isCurrentTransactionReadOnly();
 
    if(txReadOnly) {
      return slaveSqlSession;
    } else {
      returnmasterSqlSession;
    }
  }
}

가변형 List 매개변수 사용, 동적 반환 함수

BaseClass.java

protected <E> void setResponse(ModelMap model, List<E> ... resListArray) {

    Box resDatas = new Box();
    int listIndex = 0;
    for (List E : resListArray) {
        resDatas.put(RepItemName.RES_LIST_PREFIX + String.format("%03d", ++listIndex), E);
    }

    //...
}

callClass.java

public void getExam00002(ModelMap model) {

    Exam00002ReqVO reqParam = getRequestVO(Exam00002ReqVO.class);

    List<Exam00002Res1VO> resList1 = mtDao.selectList("mt.exam.em.EmNee.selectNewExamStudentChk1", reqParam);

    List<Exam00002Res2VO> resList2 = mtDao.selectList("mt.exam.em.EmNee.selectNewExamStudentChk2", reqParam);

    //여기처럼
    List[] resList = {resList1, resList2};      

    setResponse(model, resList);
}
또는 아래처럼 Arrays.asList를 사용해도 됨.
BassClass.java
protected <E> void setResponse(ModelMap model, List<E> resListArray) {

    Box resDatas = new Box();
    int listIndex = 0;
    for (E list: resListArray) {
        resDatas.put(RepItemName.RES_LIST_PREFIX + String.format("%03d", ++listIndex), list);
    }

    Box resParamBox = new Box();
    resParamBox.put(EnpApiConst.SpParamName.ERR_CD, EnpApiConst.SpValue.SUCCESS_CD);
    resParamBox.put(EnpApiConst.SpParamName.ERR_MSG, EnpApiConst.SpValue.SUCCESS_MSG);

    //...
}
callClass.java
import java.util.Arrays;

public void getExam00002(ModelMap model) {
    Exam00002ReqVO reqParam = getRequestVO(Exam00002ReqVO.class);

    List<Exam00002Res1VO> resList1 = mtDao.selectList("mt.exam.em.EmNee.selectNewExamStudentChk1", reqParam);

    List<Exam00002Res2VO> resList2 = mtDao.selectList("mt.exam.em.EmNee.selectNewExamStudentChk2", reqParam);

    setResponse(model, Arrays.asList(resList1, resList2));
}

java enum

java enum object
public enum JWT_CERT {   
    API_ADMIN("apiadmin", "apiadmin2020"),
    API_TEST("apitest", "apitest2020"),
    ETOOS("apitest", "apitest2020");
    
    private String id;
    private String key;
    
    JWT_CERT(String id, String key){
      this.id = id;
      this.key = key;
    }
    
    public String getId() {
      return id;
    }
    
    public String getKey() {
      return key;
    }
  }

html5 download attribute를 활용한 file download ( ie, edge 포함)

html
<!DOCTYPE html>
<html>
<body>
  <a href="data:text/plain;charset=utf-8,'aaaaaaa'" download="aa.txt" id="aFi-file-download"></a>
  <script>
    function file_download(str, filename){
      var file = new Blob([str],{type: "text/plain;charset=utf-8"});
      if(window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(file, filename);
      } else {
        document.getElementById("aFi-file-download").href= "data:text/plain;charset=utf-8," + str;
        document.getElementById("aFi-file-download").download = filename;
        document.getElementById("aFi-file-download").click();
      }
    }
  </script>
</body>
</html>
call
file_download("abc", "wiz.txt");

xml to file

html
<!DOCTYPE html>
<html>
<body>
<a href="data:text/plain;charset=utf-8,'aaaaaaa'" id="aFi-file-download"></a>
<script>
function file_download(xmlstr, filename) {
  document.getElementById("aFi-file-download").href = "data:text/plain;charset=utf-8," + xmlstr;
  document.getElementById("aFi-file-download").download = filename;
  document.getElementById("aFi-file-download").click();
};
</script>

</body>
</html>
call
this.Button00_onclick = function(obj:nexacro.Button,e:nexacro.ClickEventInfo)
this.Button00_onclick = function(obj:nexacro.Button,e:nexacro.ClickEventInfo){ 
  var xml = '<?xml version="1.0" encoding="UTF-8"?><Sap><resultOtherCode>Y</resultOtherCode><tprtvrtlchtList><tprtvrtlchtVO><sn>BD00120190000004</sn><cmpnyCd>LENC</cmpnyCd><prufDe>20190131</prufDe><chitTyCd>DB</chitTyCd><pstngDe>20190131</pstngDe><crncyCd>KRW</crncyCd><vrtlchtNo>BD00120190000004</vrtlchtNo><hderTextCn>gwweb1/10081/정보시스템팀</hderTextCn><inputerEmpno>20090204</inputerEmpno><inputerDeptCd>10081</inputerDeptCd><moinSanctnNo>PD20094FE0D554016B93FBB89ACAD6C17</moinSanctnNo><accnutYear>2019</accnutYear><chitNo>5090000003</chitNo><chitCreatAt>Y</chitCreatAt><chitCreatResultCn>5090000003 전표가 LENC 회사 코드에 전기되었습니다.</chitCreatResultCn></tprtvrtlchtVO></tprtvrtlchtList></Sap>';
  file_download(xml, "aa.xml");
};

xml to json

this.gfn_FiXmlToJson = function( pXmlStr ) {
try {
var obj = {};
if (pXmlStr.children.length > 0) {
for (var i = 0; i < pXmlStr.children.length; i++) {
var item = pXmlStr.children.item(i);
var nodeName = item.nodeName;
if (typeof (obj[nodeName]) == “undefined”) {
obj[nodeName] = this.gfn_FiXmlToJson(item);
} else {
if (typeof (obj[nodeName].push) == “undefined”) {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(this.gfn_FiXmlToJson(item));
}
}
} else {
obj = pXmlStr.textContent;
}
return obj;
} catch (e) {
trace(e.message);
}
};

호출할때,

this.div_Detail_ful_uploadXml_onitemchanged = function(obj:nexacro.FileUpload,e:nexacro.FileUploadItemChangeEventInfo){
var oReader = new FileReader();
var oThis = this;
oReader.onload = function(e) {
var oParser = new DOMParser();
var oXmlDoc = oParser.parseFromString(oReader.result, “text/xml”);
if (oXmlDoc.documentElement){
this._xml = oXmlDoc.documentElement;
var oJson = oThis.gfn_FiXmlToJson(oXmlDoc.documentElement);
var sElctrnTaxBillNo = oJson.TaxInvoiceDocument.IssueID; //전자세금계산서번호
var sVndcstNm = oJson.TaxInvoiceTradeSettlement.InvoicerParty.NameText; //거래처명
var sVndcstNo = oJson.TaxInvoiceTradeSettlement.InvoicerParty.ID; //거래처번호
var sSplpc = oJson.TaxInvoiceTradeSettlement.SpecifiedMonetarySummation.ChargeTotalAmount; //공급가액
var sVat = oJson.TaxInvoiceTradeSettlement.SpecifiedMonetarySummation.TaxTotalAmount; //부가세액
var sPymntTotamt = oJson.TaxInvoiceTradeSettlement.SpecifiedMonetarySummation.GrandTotalAmount; //지불총액
….
}
};
oReader.readAsText(obj.filelist[0]._ref_file);  };

xml read

aa.html

<html>
<head>

</head>
<body>
<input type=”file” onchange=”readfile(this)” >

<script>
function xml2json(xml) {
try {
var obj = {};
if (xml.children.length > 0) {
for (var i = 0; i < xml.children.length; i++) {
var item = xml.children.item(i);
var nodeName = item.nodeName;

if (typeof (obj[nodeName]) == “undefined”) {
obj[nodeName] = xml2json(item);
} else {
if (typeof (obj[nodeName].push) == “undefined”) {
var old = obj[nodeName];

obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xml2json(item));
}
}
} else {
obj = xml.textContent;
}
return obj;
} catch (e) {
console.log(e.message);
}
};

function readfile(fileinputobj){
var reader = new FileReader();

reader.onload = function(e) {
//alert(reader.result);
//Using DOMParser to get XMLDocument
var parser = new DOMParser(),
xmlDoc = parser.parseFromString(reader.result, “text/xml”);

if (xmlDoc.documentElement){
console.log(xmlDoc.documentElement);
var oJson = xml2json(xmlDoc.documentElement);
console.log(“json(to) : ” + oJson.to);
console.log(“json(from) : ” + oJson.from);
//xmlDoc.documentElement.nodeName == ‘urlset’
}

//Using DOM interpreter to get HtmlDocument
var doc=document.createElement(“div”);
doc.innerHTML=reader.result;
if (doc.querySelector(‘urlset’)){
console.log(doc.querySelector(‘urlset’));
//doc.querySelector(‘urlset’).tagName == ‘urlset’
}
}

reader.readAsText(fileinputobj.files[0]);
}
</script>
</body>
</html>

 

aa.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don’t forget me this weekend!</body>
</note>