아래 세 군데의 Reference사이트를 참고하여, 간단하게 xls 다운로드 하는 spring기능을 만들어 보았다.

기존 3가지가 다 약간씩 장점이 있으나, 복잡한 면이 있어서 이들을 섞으니 간단하게 된다.



    참고0: https://okky.kr/article/421321

   참고1: http://pkbad.tistory.com/26

   참고2:  http://heowc.tistory.com/66 



1. xml 설정.


<!-- 엑셀 Download용 View  -->

<beans:bean class = "org.springframework.web.servlet.view.BeanNameViewResolver">

    <beans:property name = "order" value = "1" />

</beans:bean>

<!-- 엑셀 Download View는 컨트롤러 리턴시 다른것들보다 먼저 읽혀야 하기 때문에 order를 0과 1로 지정-->

<beans:bean class = "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

    <beans:property name = "order" value = "0" />

    <beans:property name = "defaultErrorView" value = "error" />

    <beans:property name = "exceptionMappings">

        <beans:props>

            <beans:prop key = "RuntimeException">error</beans:prop>

        </beans:props>

    </beans:property>

</beans:bean>

<beans:bean name="ExcelXlsView" class="my.common.view.ExcelXlsView" />



2.  ExcelXlsView class 작성.


@Component

public class ExcelXlsView extends AbstractXlsView {


@Override

protected Workbook createWorkbook(Map<String, Object> model, HttpServletRequest request) {

return (HSSFWorkbook)model.get("workbook");

}

 

@Override

protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) {


    response.setCharacterEncoding("UTF-8");

            response.setContentType("application/vnd.ms-excel");

            response.setHeader("Pragma","public");

            response.setHeader("Expires","0");

        

//file이름 및 확장자

response.setHeader("Content-Disposition",

                 "attachment; filename=\"" + model.get("fileName") +".xls" + "\"");

}

}



3. Controller에서 excel 다운로드 수행.


@RequestMapping(value="/ExcelDownload.do")

public ModelAndView ExcelDownload(ModelMap modelMap, @ModelAttribute("modelVO")myVo infoVO,  

HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {

//화면의 List와 똑같은 Query수행.

List<MyVo> resultList = service.selectList(infoVO);


//Excel 생성

Workbook xlsWb = new HSSFWorkbook();

Sheet sheet1 = xlsWb.createSheet("sheet1");

Row row = null;

Cell cell = null;

    //Header Row생성

    row = sheet1.createRow(0);

    

    //필드별 헤더설정.

    int k=0;

    

    cell = row.createCell(k++);   

    cell.setCellValue("번호");


    

    sheet1.setColumnWidth(k, 4000); //좀 넓은 column은 width설정. 4000정도하면 날짜가 여유있게 들어감.

    cell = row.createCell(k++);   

    cell.setCellValue("생년월일");

    

    

    

 //Data 출력

        for(int i = 0; i < resultList.size(); i++) {

        row = sheet1.createRow(i+1);

        JdnumBunJadonVo oneRow = resultList.get(i); 

        int j = 0;

        //필드별 값설정.

        cell = row.createCell(j++);

        cell.setCellValue(oneRow.getNo());

        

        cell = row.createCell(j++);

        cell.setCellValue(oneRow.getBirthday());

        }


//model에 data넣어서, modelAndView 리턴.

        modelMap.put("workbook", xlsWb);

        modelMap.put("fileName", "excelList_" + CommonUtil.getCurrentDate()); //파일네임 앞부분 설정(.xls는 자동추가됨)

        

return new ModelAndView("ExcelXlsView");


}




4. 마지막으로, jsp에서는 아래와 같이 실행.


      var url = '/ExcelDownload.do'; //+parameter  를 get방식으로 설정.

window.open(url, '_blank' ); 

Posted by yongary
,

_json파일을 만들어서, _bulk로 elastic에 데이타를 넣는게 가장 빠른것으로 보인다.

단, batch파일은 10만건 정도가 적당하고..

이렇게 할 경우 batch파일이 너무 많아지므로,

아래와 같이 shellscript를 만들어서 일괄 삽입하는 게 좋다.


윈도우즈의 경우는 git 윈도우용을 깔아서, git bash등에서 실행하는 걸 추천한다.




#!/bin/sh


for ((i=130;i<258;i++)); do

fName='@modonBatchElastic'$i

RUN_COMMAND='curl -u elastic:changeme -s -H Content-Type:application/x-ndjson 

                   -XPOST 210.92.91.234:9210/_bulk --data-binary '$fName

echo $RUN_COMMAND

echo `$RUN_COMMAND`

done




참고: json포맷 - 2줄당 data한건 삽입

{ "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } }

{ "field1" : "value1" }

{ "index" : { "_index" : "test", "_type" : "type1", "_id" : "2" } }

{ "field1" : "value2" }

Posted by yongary
,

이더리움 KeyStore

블록체인 2018. 5. 18. 09:31

REF


이더리움에서 private키는 KeyStore라는 파일을 이용해 암호화해서 관리한다.

물론 이렇게 하지 않아도 되지만 위험하므로, 일반적으로 안전성을 위해 이렇게 관리한다.


keyStore파일 + 패스워드조합을 통해  privateKey를 관리한다.

Posted by yongary
,

REF: 20분만에 토큰배포 영문사이트


truffle환경에서 zeppelin을 이용해 토큰을 생성하는 방법 및 예제. 



<Zeppelin>


Zeppelin기반으로 Token을 만들고 싶다면..

   1. npm방식으로 zeppelin을 설치하는 방법과

   2. ethpm방식으로 zeppelin을 설치하는 방법이 있는데..   



  1.1  $ npm  install  zepplin-solidity

       혹은   package.json 이용 추천:
      => node_modules/zepplin-solidity 폴더 생성됨.

     

아래처럼 package.json을 만들고..   $ npm intall로 설치함.

{
"name": "truffle",
"version": "0.1.0",
"private": true,
"dependencies": {
"zeppelin-solidity": "1.9.0"
},
"devDependencies": {},
"scripts": {} } 


  ==>   2. Token생성.으로 이동.


  1-2.ethpm방식 (현재 비추)

    딱 필요한 것만 받는 ethpm방식이 더 좋을 수도 있는데

현재 1.9.0을 못 받고, 1.3.0을 받아오는 문제가 있다..  (일단 pass)

아래와 같이 ethpm.json파일을 만들고

  

  ethpm.json 파일

{
"package_name": "zeppelin",
"version": "1.9.0",
"description": "Secure Smart Contract library for Solidity",
"authors": [
"Manuel Araoz <manuelaraoz@gmail.com>"
],
"keywords": [
"solidity",
"ethereum",
"smart",
"contracts",
"security",
"zeppelin"
],
"license": "MIT"
}

 




$truffle install zeppelin  하면 intalled_contracts밑에 패키지가 설치가 된다..    REF


토큰관련 코딩후에는 그냥 

$truffle compile -> $truffle migrate  로 다른 일반 contracts와 함께 개발/배포 함. 



($truffle publish는 아직은 필요없는거 같은데.. 이건 ROPSTEN용도이려나? .... 아직 미 test중)



2. 그 후 Token solidity생성.


pragma solidity ^0.4.23;


import "../node_modules/zeppelin-solidity/contracts/token/StandardToken.sol";



contract ATZToken is StandardToken{

uint public INITIAL_SUPPLY = 10000000; //100만개 나누기 decimals(10**decimals)으로 표시됨.
string public name = 'Test ATZ Token';
string public symbol = 'ATZ';
uint8 public decimals = 1; //토큰을 얼마나 잘게 나눌수 있느냐. 10**X
address owner;

bool public released = false;

function ATZToken(){
totalSupply_ = INITIAL_SUPPLY * 10 ** uint(decimals);
balances[msg.sender] = INITIAL_SUPPLY; //각 계정별 잔액 저장. 상속받아 자동생성
owner = msg.sender;
}

function transfer(address to, uint256 value) public returns (bool) {
super.transfer(to, value);
}
function allowance(address owner, address spender) public view returns (uint256) {
super.allowance(owner, spender);
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public returns (bool) {
super.approve(spender, value);
}

}

그 후에,
truffle/migrations 폴더 밑에
2. _deploy_contracts.js에 ATZToken을 추가하고

$ truffle compile
$ truffle migrate (--reset) 하면 ganache등에 배포가 된다.




 






3. 회원가입등의 process가 발생할 때마다, 특정 회원에게 Token을 보내기..작성예정. REF

Posted by yongary
,

springboot에 포함된 tomcat과 함께 배포해서 바로 서비스로 돌릴 수 있다.


jar파일을 묶어서 배포하면 되고, java -jar xxx.jar 로도 실행가능하며 tomcat까지 돌아간다.


혹시 서비스로 설정을 해서 돌리고 싶다면 여기참조: REF

Posted by yongary
,

reactstrap

React.js 2018. 4. 19. 21:27

react에서 사용하는 bootstrap4라고 보면 된다.

다양한 컴포넌트들이 만들어져 있어서 가져다 쓰기만 하면 된다.


 사전준비: 1. npm install bootstrap --save

                2.  index.js 에 import 'bootstrap/dist/css/bootstrap.min.css';  추가.




<개인적으로 맘에 드는 component들> 


Navbar: http://reactstrap.github.io/components/navbar/ 


Card : 상품나열


Carousel : 슬라이드 쇼같은 느낌.

Posted by yongary
,

js HashMap 정수용

javascript 2018. 4. 16. 17:40

예전에는 아래 방식이 좋다고 생각했었는데,

최근엔 그냥 json을 hashMap으로 써도 충분한것 같다. (좀 늦으려나?)

 

let hm = {}

hm['key1']  = 2

hm['key2'] = 3

 

==> 이렇게 하면 바로 hashMap처럼 사용가능.  hm = {key1:2, key2:3} 이며, 이렇게 저장해도 됨.

 

--------------- 아래 --------------

REF 를 수정해서 만듦.

<javascript용 정수를 자동 add해주는 HashMap>

 

Map = function(){

 this.map = new Object();

};   

Map.prototype = {   

    put : function(key, value){   

 if (typeof this.get(key) == 'undefined')

             this.map[key] = value;

       else

 this.map[key] = this.map[key]+value;

    },   

    get : function(key){   

        return this.map[key];

    },

   

    //밑에 함수들은 사실 별필요 없음, 검증도 필요하고..

    containsKey : function(key){    

     return key in this.map;

    },

    containsValue : function(value){    

     for(var prop in this.map){

      if(this.map[prop] == value) return true;

     }

     return false;

    },

    isEmpty : function(key){    

     return (this.size() == 0);

    },

    clear : function(){   

     for(var prop in this.map){

      delete this.map[prop];

     }

    },

    remove : function(key){    

     delete this.map[key];

    },

    keys : function(){   

        var keys = new Array();   

        for(var prop in this.map){   

            keys.push(prop);

        }   

        return keys;

    },

    values : function(){   

     var values = new Array();   

        for(var prop in this.map){   

         values.push(this.map[prop]);

        }   

        return values;

    },

    size : function(){

      var count = 0;

      for (var prop in this.map) {

        count++;

      }

      return count;

    }

};

 

var map = new Map();

map.put("ag", 5);

map.put("ag", 2);

map.get("ag");  ===> 7

Posted by yongary
,

pure compoennet, ref등

React.js 2018. 4. 15. 21:56

<주요키워드>

className : 리액트에선 class가 아니라 className으로 써야 한다. css도 적용될 듯.

props   : extends Component엔 자동으로 들어오고,   Functional Component는 선언시 꼭 인풋으로 선언한다.

this.state  :   this.setState로  state변수를 바꿔야 하며 이 setState함수를 통해 redraw(=Update)가 발생한다. 
                    처음 그릴땐 Mount라 부르고, 그 이후부터는 Update라 부른다.




<Unique ID>

react에서 <ul>과 같은 list들에선  일반적으로 unique한 ID가 필요하다. (향후 선택을 위해서..)

array 데이타를 ul안에서 사용할 경우 array의 index를 사용해도 된다.

데이타 세팅시에는 UniqueId를 많이 사용한다.  

 

import UniqueId from 'react-html-id';

class App extends Component {

constructor() {
super();
UniqueId.enableUniqueIds(this);

this.state = { //uniqueID를 쓰려면 this때문에 생성자에서?
users: [
{id:this.nextUniqueId(), name:'Kim', age:10},
{id:this.nextUniqueId(), name:'Lee', age:20}
]
}
//array.findIndex( )로 true리턴해서 쉽게 찾을수 있음.
}
render() {
return (
<div className="App">
<ul>
{
this.state.users.map((user,index) => {
return (<User age={user.age} id={user.id} index={index}>{user.name}</User>)
})
}
</ul>
</div>
);
}
}




<Router>  REF , youtube


react에선 java-spring의 controller처럼 url을 관리해주는 메커니즘이 router이다.

url을 파라미터로 받을 수도 있다.

Link, NavLink, Redirect, Prompt도 유사하다.


   dependeny 필요: react-router-dom


   props:   exact : 정확한 매치만 허용,  strict:마지막 슬래쉬 까지도 정확히 체크


   match:  마치 props를 사용하듯이, Router에서는 match를 사용해  파라미터를 받아서 사용할 수 있다.

     => const User = ({match})  => {}  에서  match.params.myVar 사용가능  (props와는 달리 {match}중괄호 필요)

     =>      <Route path="/user;:myVar"  component={User} /> 이렇게 선언해 놓아야 함.

    

      match.url도 이용가능.



<Fragment>

  div를 2개써야 한다던지 할때 그 외부를  또 div로 싸도 되긴 하지만

 일부러 이렇게 div를 넣지 않아도 되게, react에서 특별히 제공하는 태그이다.

 실제 렌더링 되지는 않고, 2개를 가상으로 묶어주기만 한다.




<pure component>    REF

일반적으로 Component를 상속해서 Mount와 Update가 발생하지만,

PureComponent를 상속하면 Mount만 발생한다. 

아주 간단한 .. 한번 만들면 update할 일이 없는 component는 PureComponent를 쓰는게 좋다.

- 하지만 조심할 필요는 있다.    




<ref>  REF : (onKeyUp 코드도 같이 있음.)

ref={(input) => { this.firstName = input; }}

를 정의하면 ${this.firstName.value}로 사용가능하다.

외부에서 App.firstName도 사용가능하다.


16.3.0 부터는 (생성자등에서) productNameRef = React.createRef(); 지원. 조금더 간단함.



<Type Check>    REF

(개인적으로는 아직, typeCheck가 많이 필요한지 필요성을 못 느끼고 있다.

백엔드를 다른 language로 하기 때문에 필요성을 못 느낀 걸 수도 있는데..

아래와 같이 3가지 type check가 존재하는 걸 보면 분명 필요성 있는 곳이 있는것 같다..)


1. 일반적으로 간단한 type check는 PropType으로 한다. 

2. 좀 더 복잡한 type check는   react-flow  (yarn을 이용한 설치)를 이용하며

3. 가장 복잡하면서 확실한 type check는 typeScript를 이용한다..확장자도 tsx로 바뀌는 만큼 무겁다.. 




Posted by yongary
,

복합Query

ElasticSearch 2018. 4. 6. 09:44

엘라스틱을 사용하다 보면 여러가지의 Query를 복합해서 사용해야 하는 경우가 있다.


잘 섞이는 Query는

  must, must_not, should  + (filter)이며 아래와 같이 "bool"로 연결한다.   REF


{
    "bool": {
        "must":     { "match": { "title": "how to make millions" }},
        "must_not": { "match": { "tag":   "spam" }},
        "should": [
            { "match": { "tag": "starred" }}
        ],
        "filter": {
          "range": { "date": { "gte": "2014-01-01" }} 
        }
    }
}


Posted by yongary
,

<truffle + react>

이더리움의 개발환경을 

truffle과 react.js를 이용해 개발환경을 구축해 보았으며

관련 소스는 여기참조 : https://github.com/frownder/graph/tree/master/react-truffle

- metamask이용 및  ganache를 이용한 로컬개발은 잘 된다.



여기에다가 토큰발행을 위해서  zeppelin-solidity 를 이용.


react+metamask 참고사이트: REF


import 'Web3' from 'web3';

// ...

componentDidMount() {

  // Check if Web3 has been injected by the browser (MetaMask).
  // (since 'web3' is global, we need to use 'window')
  if (window.web3 && window.web3.currentProvider.isMetaMask) {
    window.web3.eth.getAccounts((error, accounts) => {

      // Do whatever you need to.
      this.setState({wallet: accounts[0]});
    });
  } else {
    console.log('MetaMask account not detected :(');
  }
}



<truffle + zeppelin>

truffle과 zeppelin-solidity를 이용한 개발 예제는

이곳을 참조:  DNEXT-POST

Posted by yongary
,

몽고db

springBoot gradle 2018. 3. 26. 23:14

springBoot2.0에서

spring-boot-starter-data-mongodb 등장.

   (localhost 27017포트의 test DB로 자동 접속.)  SpringBoot2.0 tutorial


@Document나 @Id는 기존과 동일.


출처:

https://m.youtube.com/watch?v=UJn_aTbmk9o



윈도우용 mongoDB설치는 : http://solarisailab.com/archives/1605 


약간예전꺼지만 spring Query예제들:  mkyong



2014년 몽고db 문제점 한글로 적은 글: REF

Posted by yongary
,

2세대 블록체인의 대세는 이더리움이고 가장 저변도 넓다.

하지만 단점을 꼽는다면, 다소 늦은 점과 사용시에 수수료가 든다는 점이다.


이를 극복하기 위해서 리눅스재단과 IBM을 중심으로 하이퍼레저가 만들어졌으며

컨소시엄을 구성해서 운영하기에 좋은 형태이다.



개인적으로 생각하는 하이퍼레저의 단점을 나열해 보면


-하이퍼레저: 컨소시엄을 구성해서 운영해야 하는 부담이 있고

    그렇게 하지 않을경우, 보안성이 떨어진다. 

   물론 하나의 회사에서 4개이상의 노드를 구성해서 운영할 수도 있지만,

   이럴 경우 서버장애로 인한 안정성도 떨어지고, 

   소스를 자체수정해서 로직의 조작등의 가능성도 있기 때문에 보안성이 떨어지는 것이다.


그래서, 개인적으로는 수수료라는 큰 단점이 있긴 하지만

이것은 보통 ICO를 통해 극복이 되는 이더리움이 더 대세가 될 것이라고 판단된다.

(물론 이더리움이 이미 대세라고 보고 있다)



<이더리움과 하이퍼레저의 차이점>

 구분

 이더리움

 하이퍼레저

 오픈시기

 2015.7

 2017.7

 가상화폐

 ETH

 없음

 합의

 POW

 PBFT(자체 알고리듬- 타3개의 노드중 1개이상의 노드의 승인 필요)

 네트워크

 Public, (private에서도 가능)

 private

 스마트계약

 주로 solidity로 구현

 chaincode로 구현

 블록체인 구분

 Public

 Private

 기술기반

 EVM(자체구현) 

 Docker




참고사이트: REF

Posted by yongary
,

react설치:   npm install -g create-react-app

프로젝트 생성:  create-react-app hello-world    REF



============= Form 예제 =================== 


class Game extends React.Component {

  constructor(props) {

super(props);


this.onSubmit = this.onSubmit.bind(this);   //onSubmit등 이벤트를 쓸때는 생성자에서, 이 window로 onSubmit을 bind

  }


  onSubmit(event) {

event.preventDefault();

console.log(this.input.value)    //   this.input으로 바로 언급가능


//const data = new FormData(event.target);

let data={};

data.name = event.target[0].value;

data.value = event.target[1].value;


fetch('/api/form-submit-url', {

method: 'POST',

body: data,

});

  }


  onClick() {                                                      //각종 이벤트 정의 가능

     console.log('test);

  }


  render() {

            const list = [ 'test1', 'test2'];   //여기서 변수 선언 가능. const나 let을 많이 쓴다. ES6문법.


    return (

      <div className="game">        //html에선 class를 쓰지만, JSX에서는 className을 쓴다.

        <div className="game-board">

          <Board />

        </div>

        <div className="game-info" onClick = {this.onClick}> //이벤트를 이런식으로 호출 가능

          <div>{/* status */}</div>

          <ol>{/* TODO */}</ol>

        </div>


         <form onSubmit={this.onSubmit}>

                 <input onChange={this.onChange}  ref={input => this.input=input} />

         </form>         

      </div>

    );

  }

}




============= setState 예제 ===================


class
 App extends React.Component {

  constructor(props) {

super(props);


this.state= {                 //JSON포맷으로 state 지정

title: 'My Title'

};

this.onClick = this.onClick.bind(this);

  }


  onClick() {

      this.setState(               //state 수정시에는 꼭, setState() 함수로 수정

            {title: 'New Title'}

      );

  }


  render() {


    return (

      <div className="App">        

<h1> {this.state.title} </h1>    //state 사용

               <div onClick = {this.onClick}> Click here </div>

               <MyComponent />    //다른  Component 그리는 방법. 혹은

               

                //혹은 아래처럼 변경하면서 사용가능 : 

                // 이경우 MyComponent render() 첫줄에는  const {title, name, onClick } = this.props;  

               <MyComponent                        

                    title =' __'

                    name = 'My Name'

                    onClick = {this.onClick}

               />

      </div>

    );

  }

}



출처유투브

Posted by yongary
,

참고)  이더리움 용어:  transaction - writing하는 호출,   call-읽는 호출.

공부하기 좋은 소스: petShop




<Truffle> : 단어 의미는 송로버섯


이더리움 solidify 개발시에 간단한 웹환경인 remix가 공부하기 좋지만,

본격적으로 빌드환경 구성해서 개발하기에는 truffle이 좋다.   


설치: $npm install -g truffle

$truffle init    만 하면 개발폴더구조와 설정파일인 truffle.js가 생성된다.

$truffle compile - sol컴파일.

 


참고: 테스트 서버환경 (테스트용도임- 배포환경으로 적당치 않음)

truffle에 직접 lite-server를 사용하여 localhost:3000으로 test를 할 수도 있는데

이 경우엔 package.json을 만들어 "dev"란 이름으로 lite-server를 추가하고

$npm run dev 를 하면 된다.     => petShop truffle예제 참고   


$truffle console - crowd세일등을 test할 때, javascript console처럼 온라인 test가능. REF


좋은 crowd세일 예제:  REF



<Ganache> : 단어 의미는 초코+크림 반반 섞은 거시기


remix에서는 이더리움 지갑으로 metaMask를 쓰듯이

Truffle에서는 이더리움 client로 ganache를 사용하는게 좋다. (물론 다른 것들도 있다)


GANACHE  :  app을 실행하면

http://127.0.0.1:7545  에서 클라이언트 실행

                                 참고 8545 = TestRPC일경우.(주로 MetaMask랑 같이 씀) - REF

                                     truffle init # Initialize a default truffle project in that folder

truffle build # Compile the dapp truffle migrate # Publish the dapp on the blockchain truffle serve # Host your web interface on port 8080


Truffle + Ganache환경에서

truffle develop하면  http://127.0.0.1:9545 에서 클라이언트 실행해줌. 



<ROPSTEN-TestNet사용법>


 $npm install truffle-hdwallet-provider -save하고 나서


 truffle.js를 편집해서 ROPSTEN설정하고

           (ethpm.js도 점검하고)

$truffle publish  하면 ROPSTEN에 publish됨.




<Zeppelin>

Zeppelin기반으로 Token을 만들고 싶다면.. npm방식으로 zeppelin을 설치하는 방법과

ethpm방식으로 zeppelin을 설치하는 방법이 있는데..   


npm방식으로 하면 다른 소스들과 헤깔리기도 하고, 직접 zeppelin과 상관도 없는 많은 파일들을 받아야 하므로

딱 필요한 것만 받는 ethpm방식으로 설치하기를 추천한다.


ethpm.json파일만 만든 후에  REF

$truffle install zeppelin하면 intalled_contracts밑에 패키지가 설치가 되고..    REF

토큰관련 코딩후에는 그냥 

$truffle compile -> $truffle migrate로 다른 일반 contracts와 함께 개발이 가능한 것으로 보인다.

($truffle publish는 아직은 필요없는거 같은데.. 이건 ROPSTEN용도이려나? .... 아직 미 test중)



출처:Truffle공식사이트

Posted by yongary
,


비트코인 블록의 헤더가 6가지 간단한 정보로 관리되는데 비해,


이더리움 블록의 헤더는 무려 15가지 정보가 관리된다.   

   바디에는 Trasaction List와  Uncle List: (유효한 블록이지만 선택이 안된  List)가 관리된다.


이더리움 블록헤더

 부모Hash

 Uncle Hash

 보상: 채굴성공에 대한 보상금

 stateRoot :  상태 trie의 rootHash값

 transactionsRoot: transaction List에서 파생된 trie의 rootHash값

 수신자Root

 Bloom필터

 난이도 

 조상 블록의 개수

 gasLimit

 gasUsed

 시간(timestamp)

 extraData

 mixHash : 

그리고, 그 유명한 NONCE


REF



이더리움은 기본적으로 블록에  (비트코인처럼)완성된 데이타가 저장   되는게 아니고,  

최종상태와 transaaction List를 관리하고 있어서,  계산을 해야 최종상태를 알수 있다. 



헤더도 마찬가지 개념으로서, 바디의 2가지 정보를 위주로 

   parentHash와 nonce를 제외한 모든 헤더정보를 만들어 낸다고 볼 수 있는데,

자세한 사항은 (공부해서 보충예정)

Posted by yongary
,

REF


이더리움에서 계산량이 많을 경우를 대비해, 계산량이 많은 부분은 별도로 sidechain에서 계산을 해서

비용을 줄이도록 만든 블록체인으로  Loom Network가 대표적이다.



Posted by yongary
,

solidity는 이더리움에서 smartContract를 정의할때 사용하는 언어로서 javascript에다가 몇가지 기능을 추가한 언어이다.


헬로월드 수준은: http://www.chaintalk.io/archive/lecture/86 

             간단한 dApp예제는 : http://www.chaintalk.io/archive/lecture/501


공부하기 가장좋은 사이트는 크립토좀비.



거기서 공부한 예제를 보면 다음과 같다.

pragma solidity ^0.4.19;

contract ZombieFactory {

// 여기에 이벤트 선언 - 이벤트는 나중에 별도로

uint dnaDigits = 16;
uint dnaModulus = 10 ** dnaDigits;

//struct: 생성자 자동, myZombie.name 으로 접근.

//struct내에서는 uint(256) 보다는 uint8을 쓰는게 가스소모량을 줄인다.

struct Zombie {
string name;
uint dna;
}

Zombie[] public zombies; //변수나 함수 되에 public/private 선언이 가능하다.

//private함수 및 param의 이름은 _로 시작하는게 관례

// internal: 자식class에서도 호출가능-private은 안됨 external: 외부에서만 호출가능

function _createZombie(string _name, uint _dna) private {
zombies.push(Zombie(_name, _dna));
// 여기서 이벤트 실행
}

//view:읽기만 하는 함수외부서호출시gas불소모, pure:다른변수 전혀 안쓰는 함수, return은 여러개도 가능

function _generateRandomDna(string _str) private view returns (uint) {
uint rand = uint(keccak256(_str)); //이더리움에서 지원하는 SHA함수로 16진수 return. uint로 변환필요
return rand % dnaModulus;
}

function createRandomZombie(string _name) public {
uint randDna = _generateRandomDna(_name);
_createZombie(_name, randDna);
}
}


<Event>

  

//선언
event NewZombieAdded(uint zombieId, string name, uint dna);

//이벤트 실행: dApp으로 신호보내기 임.
NewZombieAdded(id, _name, _dna); //id= zombies.push(..)-1 로 가능. push는 length리턴.


  이벤트 받는 예제는 : REF


<Mapping> 매핑은 말이 Mapping이지 사용법을 array와 동일하게 만들어 놨음.
      msg.sender 이용(해보자) : 컨트랙트내의 함수를 외부에서 호출한 사람주소


mapping (address => uint) favoriteZombieMap; function setMyNumber(uint _myNumber) public { // `msg.sender`에 대해 `_myNumber`가 저장되도록 `favoriteNumber` 매핑을 업데이트한다 ` favoriteZombieMap[msg.sender] = _myNumber; // ^ 데이터를 저장하는 구문은 배열로 데이터를 저장할 떄와 동일하다 }


<Require> Require는 if 함수와 비슷하지만,  조건이 안 맞으면 에러를 낸다.  

  solidity에는 string비교함수가 없으므로 SHA해시로 비교한다. 

require(keccak256(_name) == keccak256("Vitalik"));



<상속> 

contract ZombieFeeding is ZombieFactory {
}

  


<storage 및 메모리>
storage: HDD 또는 heap느낌.  블록체인에 영구저장됨.  contract의 멤버변수들도 여기 해당됨.
memory: RAM 또는 stack느낌.

대부분 storage/memory구분없이 사용해도 자동으로 되긴 하지만, function내에서 struct/array처리시 구분해서 사용해야할 경우가 있다.


<Interface>  

contract와 포맷이 동일한데, 내부함수에 body없음.

=> 다른 contract내의 함수를 호출할때 사용한다.

contract KittyInterface {
function getKitty(uint256 _id) external view returns (uint a);
}



<OpenZeppelin의 Ownable.sol>  => 이걸 상속받으면  onlyOwner modifier로 간단히  owner제약.  

owner 만 실행가능함. 

//1. import ownable.sol, 2. 상속 (is Ownable) 3.아래처럼 사용

function setKittyContractAddress(address _address) external onlyOwner {
kittyContract = KittyInterface(_address);
}


onlyOwner와 같은 modifier에 인자도 추가 가능.

modifier aboveLevel(uint _level, uint _zombieId) {
require(zombies[_zombieId].level > _level);
_; //실행코드가 한줄은 필요..
}



<각종 시간>

1 minutes :  60  임 (초단위까지 네요)

5 minutes: 300 

 secondsminuteshoursdaysweeksyears 같은 시간 단위 또한 포함하고 있다네. 이들은 그에 해당하는 길이 만큼의 초 단위 uint 숫자로 변환되네. 즉 1 minutes는 601 hours는 3600(60초 x 60 분), 1 days는 86400(24시간 x 60분 x 60초) 같이 변환

// 마지막으로 `updateTimestamp`가 호출된 뒤 5분이 지났으면 `true`를, 5분이 아직 지나지 않았으면 `false`를 반환 function fiveMinutesHavePassed() public view returns (bool) { return (now >= (lastUpdated + 5 minutes)); }



<Payable>

function levelUp(uint _zombieId) external payable {
require(msg.value == levelUpFee);
zombies[_zombieId].level++;
}


//인출 코드 예제.
uint itemFee = 0.001 ether; msg.sender.transfer(msg.value - itemFee);



Posted by yongary
,


build.gradle에서 npm run build 수행방법:


plugins {
id "com.moowork.node" version "1.2.0"
}
apply plugin: 'com.moowork.node'
task npmBuild(type: NpmTask) {
args = ['run-script','build']
}
build.dependsOn npmBuild



그리고, jar하면서 react.js의 결과파일을 static으로 넣는 방법은

 web-frontend 프로젝트를 별도로 만들고, (위의 build.gradle작업은 여기서 하고)


메인 spring-boot-webapp 프로젝트의 build.gradle에서   아래와 같이  의도적으로 build밑에껄 복사해준다.

jar {
//blabla
from {
configurations.compile.collect {it.isDirectory()? it: zipTree(it)}
}
into('static') {
from('../web-frontend/build')
}
}


Posted by yongary
,

Ajax axios, Redux

React.js 2018. 2. 25. 23:26


React에서 ajax기능을 사용할때는 axios HttpClient를 많이 사용한다.   REF



  axios.get('/user?id=velopert')

    .then( response => { console.log(response); } ) // SUCCESS
    .catch( response => { console.log(response); } ); // ERROR

axios.post('/msg', { user: 'velopert', message: 'hi' }) .then( response => { console.log(response) } ) .catch( response => { console.log(response) } ); //catch는 생략가능

//IE 호환문제 ? babe-polyfill로 해결? -> test해보자.

class 활용 예제. 

https://laracasts.com/discuss/channels/servers/get-data-out-from-axios-javascript



Redux 는 study중:    dispatcher방식으로 state관리  https://velopert.com/1225   




=================물론 jquery $.ajax도 사용할 수 있다 =================


 (POST앞에 있는것은 커서임)


출처:유투브



Posted by yongary
,

키보관 방법

블록체인 2018. 2. 18. 00:03

키나 IOTA seed를 암호화해서 보관하고 싶으면


파일을 알집으로 암호넣어서 zip을 한다음에


axcrypt.net에서 프로그램을 다운받아서 아주 긴 비번으로 로그인을 해서, 암호화를 하도록 한다.

256bit 알고리듬으라 안전하다.  



Posted by yongary
,

kubernetes

SDN,cloud,Puppet 2018. 2. 12. 19:19

Docker를 여러개의 host에서 쓴다던지 하는 경우로 인해,

서로 다른 Host내의 docker끼리 통신을 해야한다면(inter-host comm.)


Kubernetes를 사용하면 된다. 

Kubernetes에는 그 외에도 몇가지 기능이 있는데.. 


Posted by yongary
,

비트코인 지갑

블록체인 2018. 2. 1. 23:07

 REF

 비트코인 지갑 : 처음들으면 Bitcoin이 들어있는 것으로 착각들을 하지만, 실제로는 private키만 보관한다.

   종류는 인터넷에 연결된 Hot Wallet과  그렇지 않은 Cold Wallet이 있고 ,   HD(계층 결정적)Wallet도 참고삼아 보자.


  Hot Wallet - full node에는 full wallet,  SPV Node에는 SPV(Simple Payment Verification) wallet. 

                     전체 blockchain을 저장하지 않으면서 full node들의 메모리를 이용하는 가벼운 장점으로 인해, 모바일을 비롯해 많은 SPV wallet들이 발전중이다.


  Cold Wallet - 종이나 USB 혹은 특별히 제작된 Hardware와 같이 offline으로 private key를 저장하는 Wallet.




  HD Wallet - 24개 이하의 단어를 쓰면 private key를 생성해줘서 약간 외울수 있는 수준의 private key를 만들어 주는 지갑.

             brain Wallet도 비슷한 개념인거 같네요.   암튼 이것도 단어는 추측이 쉬워서 보안에 취약하다는 거...  

        정리하면) 단어를 이용해 pk를 만들거나 단어를 통해 pk를 암기하는 방식으로 pk를 안외워도 되는 방식이지만 보안에 썩 좋진 않음

        ==> 그래도  왠지 이게 끌리네요. 가성비가 좋을듯. 



 -------------  private key를 보관하지 않는 wallet --------  비트코인 지갑이라고 부를수 없을것 같구요

  Web Wallet- pk를 3자에게 맡긴 것으로, 거래소 등에 Wallet을 맡겼다고 보면 된다.  당근 위험!  

Posted by yongary
,

jQuery의 팝업 기능으로 간단히 이쁜 layer팝업을 만들수 있다.

 - 이걸 모를때는 bootstrap을 사용했었는데, jQuery가 더 편하다.

  (이쁘기는 bootstrap이 더 이쁠 것 같아요)



- 사용법도 간단하다.  REF


1. jquery관련 인클루드

  <script type="text/javascript" src="blabla/js/jquery.popup.min.js"></script>


2. html 팝업코딩

  <div id="popup" class="pop_style">

     blabla

  

3. jquery로 호출.

  뛰우기:  $('#popup').bPopup();


  close:   $('#popup').bPopup().close();

Posted by yongary
,

Excel upload

springBoot gradle 2018. 1. 23. 11:46

 poi 이용 : 한글 REF 

    영문: REF



1. maven dependency 추가.

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi</artifactId>

<version>3.15</version>

</dependency>

         <dependency>

            <groupId>org.apache.poi</groupId>

            <artifactId>poi-ooxml</artifactId>

            <version>3.15</version>

        </dependency>

<dependency>

            <groupId>org.apache.poi</groupId>

            <artifactId>poi-ooxml-schemas</artifactId>

            <version>3.15</version>

        </dependency>

        <dependency>

            <groupId>org.apache.poi</groupId>

            <artifactId>poi-contrib</artifactId>

            <version>3.6</version>

        </dependency>


2. JSP

function fnCheckUpload() {

var file = $("#excel").val();

if(file == "" || file == null){

alert("먼저 파일을 선택하세요.");

return false;

}

var fileFormat = file.split(".");

var fileType = fileFormat[1];

if(confirm("업로드 하시겠습니까?")){

$('#excelUpForm').attr('action','/uploadMoveinExcel.do');

var options = {

fail:function(data) {

        alert('저장 오류가 발행하였습니다.');

        $('#popup').bPopup().close();

        },

success:function(data){

alert(data + "건 업로드 완료");

$('#popup').bPopup().close();

},

type: "POST",

data : {"excelType" : fileType}

};

$('#excelUpForm').ajaxSubmit(options);

}

}

-----HTML--------

<form id="excelUpForm" method="post" action="" role="form" enctype="multipart/form-data">

                                    <input  id="excel" name="excel" class="file" type="file"  >


</form>



3. controller

  @ResponseBody

@RequestMapping(value="/uploadMoveinExcel.do")

public String uploadExcel( MultipartHttpServletRequest request, HttpSession session) {

List<ExcelVo> list = new ArrayList<>();

String excelType = request.getParameter("excelType");

log.info("uploadExcel.do + excelType:" + excelType);

if(excelType.equals("xls")){

list = moveinService.xlsExcelReader(request);

}else if(excelType.equals("xlsx")){

//IN_STUDY:  list = adminAccountsMngService.xlsxExcelReader(req);

}

int cnt = service.uploadList(list);

return String.valueOf(cnt);//success cnt : media처리의 경우, JSON포맷으로 잘 안변함(config필요), 따라서 간단히 숫자만 리턴.

}


4. service

  public List<MoveinExcelVo> xlsExcelReader(MultipartHttpServletRequest request) {

// 반환할 객체를 생성

List<MoveinExcelVo> list = new ArrayList<>();


MultipartFile file = request.getFile("excel");

HSSFWorkbook workbook = null;


try {

// HSSFWorkbook은 엑셀파일 전체 내용을 담고 있는 객체

workbook = new HSSFWorkbook(file.getInputStream());


// 0번째 sheet 반환

HSSFSheet curSheet = workbook.getSheetAt(0);  //workbook.getNumberOfSheets()

// row 탐색 for문

boolean isInTable = false;

for (int rowIndex = 0; rowIndex < curSheet.getPhysicalNumberOfRows(); rowIndex++) {

//헤더 Cell 찾기.

String firstCellValue = curSheet.getRow(rowIndex).getCell(0).getStringCellValue();

if ("구분".equals(firstCellValue.trim())) { //table헤더 발견.

isInTable = true;

continue; //헤더는 pass.  (다움줊부터 paring시작.)

}

if (isInTable) { //in Table 파싱 시작. ///////////////////////////////////////////

HSSFRow curRow = curSheet.getRow(rowIndex);

//필수 Cell들.

String cellStr = curRow.getCell(2).getStringCellValue(); //String 읽기

String cellDate =  StringUtil.toYYMMDD(curRow.getCell(5).getDateCellValue()); //날짜 읽기

String cellNum = curRow.getCell(7).getNumericCellValue() + ""; //산차.

  String cellLongNUm = StringUtil.toIntString(curRow.getCell(12).getNumericCellValue() ;   //엄청 긴 숫자 읽기

. . . . 

} catch (IOException e) {

e.printStackTrace();

}


// vo로 만들면서 db에 삽입코드는 생략.

return list;

}


public class StringUtil {


    private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    public static String datePattern = "^\\d{4}[\\-](0[1-9]|1[012])[\\-](0[1-9]|[12][0-9]|3[01])$";

    public static boolean isDate(String str) {

    return Pattern.matches(datePattern, str);

    }

    //return YYYY-MM-DD String

    public static String toYYMMDD(Date date) {

    return formatter.format(date);

    }

    public static boolean isNumericOrFloat(String str) {

        if (str == null) {

            return false;

        }

        int sz = str.length();

        for (int i = 0; i < sz; i++) {

            if (Character.isDigit(str.charAt(i)) == false) {

            if (str.charAt(i) != '.')  //Added KY. '.'도 numeric으로 간주. float때문에.

            return false;

            }

        }

        return true;

    }

    

    //For Excel processing.

    // 엑셀에선 숫자를 항상 double로 읽기 때문에 int형태의 String으로 변환하면 유용.

    public static String toIntString(double doubleVal) {

    try {

    BigInteger k = new BigDecimal(doubleVal).toBigInteger();

    

    return String.valueOf(k);

   

    } catch (Exception e) {

    return null;

    }

    }

Posted by yongary
,

특수기능

ElasticSearch 2018. 1. 22. 21:38

template: 여러개의 template을 지정해 놓을 수 있음.

     -> 잘못 사용하면 여기에 계속 걸려서, insert가 안되는 경우도 있으니 조심필요.



join: 부모-child관계 지정.   (예:질문-답변)  REF

       RDB의 relation과 어느정도는 유사하게 사용이 가능하지만,

       one-to-many 관계에서만 사용하는 게 좋다. 

       (그리고, 한 index안에서만 사용한다 )


 -Relation: 부모와 자식관계 설정

 -Child 여러 개 설정 가능

- (손자)Child 밑에 Child를 둘 수 있음





_segment: segment내의 data까지 조회가 가능하다.





Posted by yongary
,

js 모듈화 코딩기법

jquery 2018. 1. 2. 09:14

http://www.nextree.co.kr/p4150/  

Posted by yongary
,

기본 Query예제

ElasticSearch 2017. 12. 31. 08:22


kibana필터 기본 문법:   REF - 루씬 문법임. . 

     title:(+return +"pink panther") : Field grouping - REF

  

timeliion 문법: REF



== 그 외 아래는 elastic 기본 Query예제이다. ====================================

 



  Index데이타넣기 + 자동생성 : REF


PUT /twitter
/doc/1 (1은 생략시 자동생성) { "user" : "kimchy", "post_date" : "2009-11-15T14:12:12", "message" : "trying out Elasticsearch" }



Index 생성 및 Mapping 조정: REF

PUT twitter :생성 {} PUT twitter/_mapping/_doc { "properties": { "name": { "type": "text" } } } //type:keyword가 중요

데이타 타입: REF



문서하나 Delete:

    DELETE /twitter/_doc/1

   


 Delete Index:

 DELETE /twitter






  Match:  REF


GET entry/_search

{

  "query": {

    "term": {"play_name":"Hamlet"}

  }

}


GET entry


GET /_search { "query": { "match" : { "message" : "this is a test" } } }



Posted by yongary
,

랜섬웨어 감염시

IT 2017. 12. 30. 10:22

랜섬웨어에 감염되어 파일들이 확장자가 변경되면서 실행이 안된다면..


1. windows/system32/tasks  밑에 가서, 날짜를 보고 최근 것들을 지운다.

  => 랜섬웨어 동작을 멈추게 한다.

  (그 후 고클린 등으로 각종 clear작업을 해주면 더 좋다)


2. 이미 감염된 파일들은 복구가 불가능 한데, 

   https://www.nomoreransom.org/ko/index.html   여기에 가면 일부 복구가 되는 랜섬들이 나열되어 있으므로

   따라서 복구를 한다.

Posted by yongary
,

spring boot로 Web Project생성하기.


1. https://start.spring.io/  에 접속해서  maven/gradle을 선택하고 이름만 넣으면  springboot프로젝트를 생성할 수 있다.  

   => 일반 application이 생성된다.


  1.1  IDEA나 eclipse에서 import project를 해서 열어서 Run만 시키면 돌아간다. (아래과 같이 spring을 볼수 있다)

    .   ____          _            __ _ _

 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )

  '  |____| .__|_| |_|_| |_\__, | / / / /

 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::        (v1.5.9.RELEASE)



2. Build.gradle을 열어서  아래 한줄을 추가한다.   (JDK1.8기준)


compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.4.7.RELEASE'
(version: '1.4.7.RELEASE')

 

   ==> 자동으로 Web Application이 된다. 실행도 되고 localhost:8080 접속도 된다.


3.  jsp처리기능이 아직없으므로 이를 위해 2개 더 추가한다. (REF1, ) 

    

compile group: 'javax.servlet', name: 'jstl', version: '1.2'
compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-core', version: '8.5.24'
compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-jasper', version: '8.5.24'

   

     (그리고, resources밑에 있는 application.property에  아래 4번 경로와 suffix를 추가한다)

     


spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp



4.  src/main  밑에  /webapp/views  밑에    jsp생성  (REF2-jsp) 

     
  jsp첫줄에는 아래 한줄이 필요하고..

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

 그 후 <html> tag야 있으면 좋고..





별첨: 간단한 Junit4 Test코드.... + RestTemplate는 여기 참조:   REF

         Lombok사용시 - 설정에서 컴파일러 옵션 중 Annotation Process 체크필요.

Posted by yongary
,

MVC개념

springBoot gradle 2017. 12. 29. 21:56

      USER가 url을 요청한다던지 하는 action을 하면, controller가 받아서 

     Model을 조회/변경하고 그걸 다시
     View에서 그려준다.  


    3가지가 분리되어서 업무분리 개발분리가 가능해진다. 

Posted by yongary
,