XML파싱 방법에는 문서전체를 로드해서 하는 DOM방식과, 문서를 순차적으로 읽으면서 하는 SAX(Simple Api 4 Xml)방식이 있다. 참고사이트


JDom등의 별도 라이브러리를 쓰는 경우도 있지만,

내장된 XPath가 워낙 간단해서 입문자는 무조건 이방식으로 하면 될 것으로 보인다.   이 XPath는 기존의 DOM 방식이나 SAX방식이 아닌

XDM(Xml Data Model)방식으로 불리는데, 굳이 Dom/SAX와 비교하자면 Dom방식에  약간 더 가깝다고 볼 수 있을 것 같다.



<사용방식>

//어딘가 Web에 연결해서

      HttpURLConnection con = (HttpURLConnection)apiUrl.openConnection();

 con.setRequestMethod("GET");


//using XPath 로 파싱.

InputSource is = new InputSource( new InputStreamReader(con.getInputStream()));

Document doc = DocumentBuilderFactory.newInstance()

.newDocumentBuilder().parse(is);

XPath xpath = XPathFactory.newInstance().newXPath();

zone = (String)xpath.evaluate("/result/zoneName", doc, XPathConstants.STRING);

String offTime = (String)xpath.evaluate("/result/gmtOffset", doc, XPathConstants.STRING);

time = timeAdd(timeCords[0], offTime);

Posted by yongary
,

1. 몇가지 Regex 샘플.


A."no it's all right lag"  제거 => str.replaceAll ("no (.*)lag", "A")

B. "Availability in 20 days";  20만 발췌 =>  str.replaceAll("\\D+", ""); 




2. json 을 파싱할 때, 필요한  Regex 2개이다.  (\=역슬래쉬)


String normal = json.replaceAll("[{\"}]", ""); //remove {,", }

String[] kvset = normal.split(",\\s*");  //split with ,   and  * means  space exist or not



Regex정리 사이트


표현식

 설명 

 ^

 문자열의 시작

 문자열의 종료

 .

 임의의 한 문자 (문자의 종류 가리지 않음)

 단, \ 는 넣을 수 없음

 *

 앞 문자가 없을 수도 무한정 많을 수도 있음

 앞 문자가 하나 이상

 앞 문자가 없거나 하나있음

 []

 문자의 집합이나 범위를 나타내며 두 문자 사이는 - 기호로 범위를      나타낸다. []내에서 ^가 선행하여 존재하면 not 을 나타낸다.

 {}

 횟수 또는 범위를 나타낸다.

 ()

 소괄호 안의 문자를 하나의 문자로 인식 

 |

 패턴 안에서 or 연산을 수행할 때 사용

 \s

 공백 문자

 \S

 공백 문자가 아닌 나머지 문자

 \w

 알파벳이나 숫자

\W 

 알파벳이나 숫자를 제외한 문자

\d 

 숫자 [0-9]와 동일

\D 

 숫자를 제외한 모든 문자

 정규표현식 역슬래시(\)는 확장 문자
 역슬래시 다음에 일반 문자가 오면 특수문자로 취급하고 역슬래시 다음에 특수문자가 오면 그 문자 자체를 의미

(?i) 

 앞 부분에 (?i) 라는 옵션을 넣어주면 대소문자를 구분하지 않음


Posted by yongary
,

가변 파라미터를 받아서 사용하는 방법: (vprintf로 출력가능 한데)

=> 약간 변조하고 싶을 때에는 vsprintf를 사용하면 된다... 



#include <stdarg.h>


void logPRINTD(const char* format, ...){ 

    char str[512];

    

va_list args;

    va_start(args, format);

    vsprintf(str, format, args);  //str로 옮기기

    strcat(str,"\n"); /////////////////////  str에 \n 더하기

    va_end(args); 


//str로 하고싶은일 하기. bla bla 

}   


Posted by yongary
,

라우팅 설정.

Linux 2015. 4. 16. 16:29

 

 

리눅스에서 실제 라우팅이 되는지 체크하는 명령어는

$traceroute 123.45.123.45   이다.

 

 

라우팅이 안되어 있다면

 $route add -net 125.159.63.14 netmask 255.255.255.255 gw 14.63.134.254 dev eth4  명령으로 추가가능.

 

삭제시에는

$ route del -net 118.49.2.0 netmask 255.255.255.0 명령어로 사용.

 

라우팅 테이블 확인은

$route 명렁어이다.     추가와 삭제 후에 이 명령어로 확인하면 된다.


(맥북에서는 $netstat -nr 이 비슷하네요)

 

 

=====껐다켜도 되게 하려면 아래 정보 추가=================

/etc/sysconfig/network-scripts/route-eth4

ADDRESS0=14.63.237.0

GATEWAY0=10.217.80.1

NETMASK0=255.255.255.0

Posted by yongary
,

pthread

Linux/Linux:c개발 2015. 4. 14. 11:28

참조: http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site/Thread/Beginning/PthreadApiReference 



Thread의 상태:

PTHREAD_CREATE_JOINABLE  : 다른 thread끝나고 동작하는 thread. (exit나 join을 호출을 통해서 자원을 반납해야 하는 thread.)

PTHREAD_CREATE_DETACHED : 독립적으로 동작하므로 종료시점 체크필요없고, 종료시 자동자원반납. 



<구조체>


typedef  long pthread_t;

struct pthread_attr {
  void *stackaddr;
  size_t stacksize;
  int detachstate;
  struct sched_param param;
  int inheritsched;
  int contentionscope;
};

typedef struct pthread_attr pthread_attr_t;
#define PTHREAD_CREATE_JOINABLE       0
#define PTHREAD_CREATE_DETACHED       1


<예제 - 심플 detatched thread 생성. >

 pthread_t id;

 pthread_attr_t attributes;  



// initialize thread attributes

    pthread_attr_init(&attributes)

    pthread_attr_setdetachstate( &attributes, PTHREAD_CREATE_DETACHED);


//create a new thread 

   pthread_create( &myId, &attributes, startFunc, args);  //args는 startFunc로 전달. 

   pthread_attr_destroy(&attributes); //자원해제 



Posted by yongary
,

gethostbyname

Linux/Linux:c개발 2015. 4. 14. 09:46

<함수 prototype>

struct hostent *gethostbyname(const char *name);

int gethostbyname_r(const char *name,
               struct hostent *ret, char *buf, size_t buflen,
               struct hostent **result, int *h_errnop);


두 함수 모두 return type은 hostent  struct 이다.


<struct hostent 구조 >

struct hostent { char *h_name; /* official name of host */ char **h_aliases; /* alias list */ int h_addrtype; /* host address type */ int h_length; /* length of address */ char **h_addr_list; /* list of addresses */ 

==> 아래쪽에 in_addr구조체의 s_addr 변수 참조. 같은 형태임. 0xff01ffff의 네트웍바이트(순서대로) 형태(255.1.255.255)

} #define h_addr h_addr_list[0] /* for backward compatibility */ The members of the hostent structure are:


h_addrtype The type of address; always AF_INET or AF_INET6 at present. h_length The length of the address in bytes. h_addr_list An array of pointers to network addresses for the host (in net- HOST_NOT_FOUND The specified host is unknown. NO_ADDRESS or NO_DATA The requested name is valid but does not have an IP address. NO_RECOVERY A non-recoverable name server error occurred. TRY_AGAIN A temporary error occurred on an authoritative name server. Try again later.



<그 외 network관련 struct들 >

           struct sockaddr_in {
               sa_family_t    sin_family; /* address family: AF_INET */
               in_port_t      sin_port;   /* port in network byte order */
               struct in_addr sin_addr;   /* internet address */
           };

           /* Internet address. */
           struct in_addr {
               uint32_t       s_addr;     /* address in network byte order */  
           };

0xffffffff의 네트웍바이트 형태.=255.255.255.255


<in_addr_t  inet_addr(hostname) 함수> 이름을 0xffffffff (255.255.255.255 효과) 형태로 변환리턴.


리턴type:  typedef uint32_t in_addr_t;   

INADDR_NONE= -1 (255.255.255.255)을 리턴하는 경우. 약간문제가 될때도 있으나 거의 괜찮음.




Posted by yongary
,

c++하나를 불러쓰는 경우

 

wrapping layer를 만들어서,

c언어에서 불러쓰면 된다.

 

예) c++파일 안에서

 

extern "C" {

MyClass* myclass_new()

{

return new MyClass();

}

..몇개 함수 더 매핑.

}

이렇게만 하면,

main. c파일안에서 아래와 같이 호출이 가능하다.

 

struct MyClass *m = myclass_new();

 

 

 

그리고  build시에는 특히 c빌드시(혹은 최종 link시에)

gcc main.c -lstdc++  추가 필요....

 

 

 

참고 blog: http://ospace.tistory.com/215 

Posted by yongary
,

아주 유용하게 쓰고 있는 자동접속 script.

전문가가 ssh_stdin 을 개발해 주셔서, 이를 이용해 쓰고 있다.


===================================자동접속 + 작업 SCIRPT ==============

#!/bin/sh



PASSWD="myPasswd!"

curDir=$(pwd)

SSH_STDIN=$curDir/ssh_stdin

sshOption="-T -o StrictHostKeyChecking=no -o ConnectTimeout=1 -o NumberOfPasswordPrompts=1"



SVR_LIST="172.25.49.135 172.25.49.136"


mpList=$(eval echo $SVR_LIST)


for i in $mpList

        do


        echo "---------"$i

        echo $PASSWD | $SSH_STDIN ssh $sshOption "root@"$i "ps -ef|grep redis"

        echo $PASSWD | $SSH_STDIN ssh $sshOption "root@"$i "nstatus"

 

  #scp를 하고 싶을때는 ..  -T옵션 빼고.. $1에 파일이름 줘서.. 아래처럼. 하면 된다.

  echo $PASSWD | $SSH_STDIN scp $sshOption $1 "root@"$i":"$1

        done



=============================ssh_stdin내용=================================

#!/bin/bash


if [ -n "$SSH_ASKPASS_PASSWORD" ]; then

    cat <<< "$SSH_ASKPASS_PASSWORD"

elif [ $# -lt 1 ]; then

    echo "Usage: echo password | $0 <ssh command line options>" >&2

    exit 1

else


read SSH_ASKPASS_PASSWORD


export SSH_ASKPASS=$0

export SSH_ASKPASS_PASSWORD


[ "$DISPLAY" ] || export DISPLAY=dummydisplay:0


# use setsid to detach from tty

# exec setsid "$@" </dev/null

exec setsid "$@"

fi

Posted by yongary
,

key

javascript 2015. 4. 2. 23:07

<key event>

document.onkeydown=checkKey;

function checkKey(e){

  if(e.keyCode=='37'){  //left Key, 38:up, 39:right, 40:down

     alert('left');

  }

}



Posted by yongary
,

closure

javascript 2015. 4. 2. 09:39

클로져에 대해서 나름대로 정리해보면,

아래와 같은 함수에서 MyClass을 outter함수라고 부를때,

내부 함수 (gettitle)가  outter의 지역변수를 계속 사용할 수 있다는 개념.  

(javascript의 initialize비용이 비싸므로, closure를 이용해서 inner함수 안에서 if(!undefined) define을 할 수 있다.)

 ==> Point: 외부함수가 종료된 이후에도 사용할 수 있다.


var that=this 로 해서, this도 많이 사용한다고 한다. 이렇게 안하면 this가 전역변수인 window를 나타낼 수 있기 때문...



function MyClass(_title){

  var title=_title;

  return{   //json스타일 객체를 return.

     getTitle:function() { return title;},

  }

}


g=MyClass('ggg');

m=MyClass('mmm');


alert(g.geTtitle());   //m.getTilte()도 잘 동작.




참조: devbox

      Nonblock

Posted by yongary
,