...작성중..
'Hadoop' 카테고리의 다른 글
| [ 하둡 인사이드 ] 3. 하둡과 보안 (0) | 2015.05.15 |
|---|---|
| [ 하둡 인사이드 ] 5. 하둡 HDFS 쓰기 (0) | 2015.05.02 |
| [ 하둡 인사이드 ] 2. Hadoop Streamming (0) | 2015.05.01 |
| 하둡 쉘 스크립트 실행 순서도 | (0) | 2015.04.27 |
| hadoop-1.2.1 이클랩스 import 하기 (0) | 2015.04.27 |
...작성중..
| [ 하둡 인사이드 ] 3. 하둡과 보안 (0) | 2015.05.15 |
|---|---|
| [ 하둡 인사이드 ] 5. 하둡 HDFS 쓰기 (0) | 2015.05.02 |
| [ 하둡 인사이드 ] 2. Hadoop Streamming (0) | 2015.05.01 |
| 하둡 쉘 스크립트 실행 순서도 | (0) | 2015.04.27 |
| hadoop-1.2.1 이클랩스 import 하기 (0) | 2015.04.27 |
* InputStream / OutputStream
* Selctor
* Channel
* ByteBuffer
* Socket소켓 통신 일반
전형적인 소켓 프로그래밍 인터렉션입니다. 서버는 대기하고, 클라이언트가 접속하면 서버는 받아드리고,
받아드리면서 클라이언트와 통신하기위한 소켓하나 만들어서 쓰레드하나 만들어서
던진후에 그 쓰레드에서 클라이언트와 입/출력.
자바 NIO
자바NIO (New I/O)는 비동기 입출력은 아닙니다.
쪼 위에 blocking 되있는걸 보실수있습니다. (타임아웃 가능)
Select 모델이라고 하지요. 소켓통신 모델에는 다양한 모델이 있으며, IOCP 모델이 빠르기로 유명함.
개인적으로 자바 NIO/NIO2 프로그래밍이 C++ 을 이용한 IOCP 프로그래밍 보다는 애매하게 느꼈던것
같습니다. (추상화 하다보니 좀 희미하다고 해야하나? 그에 반해 IOCP 모델은 굉장히 클리어 하죠.)
하둡 스트리밍
사실 하둡 스트리밍에 대한 글을 쓸까 말까 좀 고민을 했었습니다. 왜냐? 할게 없기때문에..
그냥 자바 소켓통신입니다. 따라서 자바소켓통신에 대한 소스레벨 분석 글을 보신다고 생각하면 편하실듯합니다. :-) 독자분이 소켓통신을 구현할때 가져다 쓰면 좋겠지요. 구태여 바퀴를 또 만들필요가 없지 않겠습니까? (이런 의미에서 Netty 를 사용하는게 좋죠. Vert.x / Couchbase / OpenTSDB 등이 사용)
위의 그림은 클라이언트에서 데이타노드로 블록ID 을 보내어 데이터를 달라고 하는 상황에서
그와 관련된 클래스들의 모식도 입니다.
소스 조각을 하나씩 살펴보겠습니다.
DFSClient
- 하둡 HDFS 읽기/쓰기 연재에서 설명 예정.
RemoteBlockReader
- 하둡 HDFS 읽기/쓰기 연재에서 설명 예정.
NetUtils
public static SocketFactory getDefaultSocketFactory(Configuration conf) {
String propValue = conf.get("hadoop.rpc.socket.factory.class.default");
if ((propValue == null) || (propValue.length() == 0))
return SocketFactory.getDefault();
return getSocketFactoryFromProperty(conf, propValue);
}
하둡 환경설정에 따라 소켓팩토리를 선정합니다. getDefaultSocketFactory 가
기본.SocketFactory.getDefault(); 참고로 소켓팩토리를 통해서 SSLSocket 을 사용할수있습니다.
SocketInputStream
생성자
public SocketInputStream(Socket socket, long timeout)
throws IOException {
this(socket.getChannel(), timeout);
}
public SocketInputStream(ReadableByteChannel channel, long timeout)
throws IOException {
SocketIOWithTimeout.checkChannelValidity(channel);
reader = new Reader(channel, timeout);
}
내부에서 Reader 를 사용합니다.
public int read(byte[] b, int off, int len) throws IOException {
return read(ByteBuffer.wrap(b, off, len));
}
public int read(ByteBuffer dst) throws IOException {
return reader.doIO(dst, SelectionKey.OP_READ);
}
원하는 데이터의 양만큼을 ByteBuffer 클래스를 통해 할당하여 요청합니다.
SocketOutputStream
public SocketOutputStream(WritableByteChannel channel, long timeout)
throws IOException {
SocketIOWithTimeout.checkChannelValidity(channel);
writer = new Writer(channel, timeout);
}
public void write(byte[] b, int off, int len) throws IOException {
ByteBuffer buf = ByteBuffer.wrap(b, off, len);
while (buf.hasRemaining()) {
try {
if (write(buf) < 0) {
throw new IOException("The stream is closed");
}
} catch (IOException e) {
if (buf.capacity() > buf.remaining()) {
writer.close();
}
throw e;
}
}
}
Reader
: SocketIOWithTimeout 를 상속받은 클래스
int performIO(ByteBuffer buf) throws IOException {
return channel.read(buf);
}
채널에서 버퍼의 크기만큼 읽는다.
Writer
: SocketIOWithTimeout 를 상속받은 클래스
public int write(ByteBuffer src) throws IOException {
return writer.doIO(src, SelectionKey.OP_WRITE);
}
int performIO(ByteBuffer buf) throws IOException {
return channel.write(buf);
}
SocketIOWithTimeout (이게 핵심)
private static SelectorPool selector = new SelectorPool();
int doIO(ByteBuffer buf, int ops) throws IOException {
if (!buf.hasRemaining()) {
throw new IllegalArgumentException("Buffer has no data left.");
}
while (buf.hasRemaining()) {
int n = performIO(buf);
if (n != 0) {
return n;
}
selector.select(channel, ops, timeout);
}
return 0; // does not reach here.
}
Buffer 에 담을 수있는 데이터가 있는지 확인한후에 , --> if (!buf.hasRemaining()) {
더이상 담을 공간이 없을때까지 --> while (buf.hasRemaining())
입력/출력을 합니다. --> int n = performIO(buf);
입력/출력한게 있으면 리턴해줍니다. --> return n;
입력/출력한게 없으면 다시 입력/출력하기 위해 대기합니다. --> selector.select(channel, ops, timeout);
static void connect(SocketChannel channel,
SocketAddress endpoint, int timeout) throws IOException {
boolean blockingOn = channel.isBlocking();
if (blockingOn) {
channel.configureBlocking(false);
}
try {
if (channel.connect(endpoint)) {
return;
}
while (true) {
int ret = selector.select((SelectableChannel)channel,
SelectionKey.OP_CONNECT, timeoutLeft);
...
}
} catch (IOException e) {
...
}
private synchronized SelectorInfo get(SelectableChannel channel)
throws IOException {
SelectorInfo selInfo = null;
SelectorProvider provider = channel.provider();
// pick the list : rarely there is more than one provider in use.
ProviderInfo pList = providerList;
while (pList != null && pList.provider != provider) {
pList = pList.next;
}
if (pList == null) {
//LOG.info("Creating new ProviderInfo : " + provider.toString());
pList = new ProviderInfo();
pList.provider = provider;
pList.queue = new LinkedList<SelectorInfo>();
pList.next = providerList;
providerList = pList;
}
LinkedList<SelectorInfo> queue = pList.queue;
if (queue.isEmpty()) {
Selector selector = provider.openSelector();
selInfo = new SelectorInfo();
selInfo.selector = selector;
selInfo.queue = queue;
} else {
selInfo = queue.removeLast();
}
trimIdleSelectors(System.currentTimeMillis());
return selInfo;
}
셀렉터를 하나만 만들면 , 여러 소켓들이 하나의 셀렉터를 통해서 , 신호를 받기때문에 효율적이지 못합니다.
따라서 각 이벤트들마다 셀렉터를 만들면, 효율적이게 운영할수있는데, 셀렉터를 풀로 만들어서
셀렉터 생성에 대한 부담을 줄였습니다. 상황에 따라서 Read / Write / Acceptor 등을 별도의 셀렉터로
등록 시키면 좋습니다. 위의 셀렉터풀 말고도 NIO에서는 ByteBuffer Pool을 만들어서 사용해도 좋습니다.
DataNode
- 하둡 HDFS 읽기/쓰기 연재에서 설명 예정.
DataXeiverServer
- 하둡 HDFS 읽기/쓰기 연재에서 설명 예정.
DataXceiver
- 하둡 HDFS 읽기/쓰기 연재에서 설명 예정.
헤즐케스트 소개
해즐케스트의 소켓 통신을 위한 클래스들
Storm 소개
Storm 의 소켓 통신을 위한 클래스들
.............. 작성중 ................
| [ 하둡 인사이드 ] 5. 하둡 HDFS 쓰기 (0) | 2015.05.02 |
|---|---|
| [ 하둡 인사이드 ] 4. HDFS 읽기 (0) | 2015.05.02 |
| 하둡 쉘 스크립트 실행 순서도 | (0) | 2015.04.27 |
| hadoop-1.2.1 이클랩스 import 하기 (0) | 2015.04.27 |
| [ 하둡 인사이드 ] 1. Hadoop RPC (0) | 2015.04.27 |
0. 인증 / 인가 / 무결성 이란 ?
인증 (Authentication) : A 라는 사람이 그 싸이트 혹은 그 서비스를 사용할수있는가? 신원 확보 목적.
인가 (Authorization) : A 라는 사람이 서비스에서 어떤것을 할수있도록 하는가 ? ( 파일 리딩만 하게하자)
무결성 : A -> B 로 어떤 메세지를 보냈을때 그 메세지가 바뀌거나 깨지지 않음을 보장하는것.
1. 암호화 / 복호화 란 ?
암호화 : 어떤 문자열 "hello world" 를 "332XF3FX_*)3" 로 바꾸는것.
복호화 : "332XF3FX_*)3" 을 다시 "hello world" 로 환원하는것.
암호화 알고리즘에는 DES , AES 등이 있다.
JAVA AEC : http://andang72.blogspot.kr/2012/02/aes.html
암호화와 복호화를 위해서는 key (비밀키) 라는것이 필요하다.
2. 대칭형 암호화
A 와 B 라는 각각의 Peer 를 상상해보자.
각각의 컴퓨터에 동일한 key 를 복사해두고, 동일한 key 를 이용해서 암호화 / 복호화를 하는것이
대칭형 암호화이다. A,B 모두를 제어권에 두고있다면 대칭형 암호화로 충분하다.
하지만 A 는 내가 관리하는데 B 를 관리할수없을경우 B 에게 나의 비밀키를 보내야하는데
그 중간에서 탈취를 당하면 탈취한사람은 A 와 B 의 비밀 이야기를 엿들을수있게 된다.
3. 공개키 암호화 ( 비대칭형 )
공개키 암호화 (비대칭형) 방법이 대칭형과 다른것은 키를 2개 만드는것이다.
비밀키 1개에서 -> 공개키,개인키 요렇게 2개!!
개인키는 자신이 가지고 있고, 공개키를 B 에게 전달한다. 전달받은 B 는 자신의 공개키를 A에게 보낸다.
공개키로 암호화하고 개인키로 복호화한다. 암호화는 누구나 할수있지만 , 복호화는 자신밖에 못하기때문에
보안을 이룰수있다.
4. 비대칭형 / 대칭형 믹스
위의 공개키암호화는 상당히 안전하지만 , 공개키/개인키를 통한 암호화/복호화는 상당히 느리다.
따라서 처음에만 공개키로 하고 다음부터는 대칭키로 암호화/복호화를 하는 전략을 쓴다.
1 .A 는 자신의 공개키를 B에게 전달한다.
2. B 는 A의 공개키로 자신의 비밀키를 암호화해서 A에게 전달한다.
3. A 는 자신의 개인키로 B 의 비밀키를 복호화한다.
4. 공유된 B 의 비밀키로 통신한다.
이 방법은 B 가 A 의 공개키를 어떻게 진짜 A 의 공개키인지 믿을수 있나? 라는 화두를 던진다.
5. 해쉬 함수
"EWEFWFWEEFWFWEWFWE32R2FF2F" 이렇게 긴 문장을
"F3F34" 요렇게 짧게 바꾸는 작업을 말한다.
해쉬된 문장을 원래 문장으로 바꾸는건 불가능하다.
해쉬를 왜 하냐면 , 짧으면 무엇이 좋을까?
1. 암호화, 복호화 할때 시간이 단축된다.
2. 원래 문장을 전송에 사용할 필요가 없어진다. 따라서 비밀번호같은것의 노출을 피할수있다.
예를들어 비밀번호를 해쉬함수를 통해서 걸러진 문장을 DB 에 저장해두면, 진짜 비밀번호를 알수는
없지만, 동일한 비밀번호로부터 나온 결과라는것은 알수있게된다.
MD5 / SHA1 같은것을 사용한다.
6. 전자 서명
상대방의 신원을 확인하기 어려운 사이버 공간에서 서로를 알아볼 수 있도록 한 쌍의 전자서명키 (공개키+개인키)를 사용하여 자신을 증명하는 것이 전자서명의 원리입니다. 공인인증기관으로부터 인증서를 발급받아 전자계약서 등에 전자서명을 하여 계약내용을 증명합니다.단지 사이버 공간이라는 환경과 모든 처리가 전자적으로 처리된다는 것이 차이점입니다.
네이버어플리케이션 전자서명의 원리 : http://helloworld.naver.com/helloworld/textyle/744920
7. 인증서
당신과 접속해있는 사람이나 웹 사이트가 믿을 수 있는지 어떻게 판단할 수 있을까? 한 웹사이트 관리자가 있다고 가정하자. 그 사람이 당신에게 이 사이트가 믿을만하다고 (심각할 정도로) 열심히 설명했다. 당신이 그 사이트의 인증서를 설치해 주기를 바라면서 말이다. 한두번도 아니고 매번 이렇게 해야한다면 귀찮지 않겠는가?
인증서는 여러 부분으로 이루어져있다. 아래는 인증서 속에 들어있는 정보의 종류를 나타낸 것이다.
인증서 소유자의 e-mail 주소
소유자의 이름
인증서의 용도
인증서 유효기간
발행 장소
Distinguished Name (DN)
- Common Name (CN)
- 인증서 정보에 대해 서명한 사람의 디지털 ID
Public Key
해쉬(Hash)
SSL의 기본 구조는 당신이 인증서를 서명한 사람을 신뢰한다면, 서명된 인증서도 신뢰할 수 있다는 것이다. 이것은 마치 트리(Tree)와 같은 구조를 이루면서 인증서끼리 서명하게 된다. 그러면 최상위 인증서는? 이 인증서를 발행한 기관을 Root Certification Authority(줄여서 Root CA)라고 부르며, 유명한 인증 기관(역주:Verisign, Thawte, Entrust, etc)의 Root CA 인증서는 웹브라우저에 기본적으로 설치되어 있다. 이러한 인증 기관은 자신들이 서명한 인증서들을 관리할 뿐만 아니라 철회 인증서(Revoked Certificate)들도 관리하고 있다. 그러면 Root CA의 인증서는 누가 서명을 했을까? 모든 Root CA 인증서는 자체 서명(Self Signed)되어 있다.
8. SSL
SSL 은 위의 4번과 동일하다. 다만 추가된것은 공개키를 인증해주는 과정이 추가되었다.
A의 공개키를 CA 기관에 전자서명을 받아서 인증서를 받은후에 (CA 에서는 자신의 개인키로 암호화함) B에게 보내준다. B는 자신의 컴퓨터에 미리 존재하는 (브라우저안에도 있음) CA의
공개키로 인증서를 확인하여, A의 공개키를 얻는다.
HTTPS 에 사용된다.
9. JCA
가) 전자 서명과 메시지 다이제스트 같은 기능에 대한 일반적인 API 제공
나) 주요 클래스들
① MessageDigest
② Signature
③ KeyPaireGenerator
④ KeyFactory
⑤ CertificateFactory
⑥ KeyStore
⑦ AlgorithmParameters
⑧ AlgorithmParameterGenerator
⑨ SecureRandom
다) 암호 서비스 제공자 Sun Provider(Java 2 기준, sun.security.provider.Sun)
① MD5 메시지 다이제스트
② SHA-1 메시지 다이제스트
③ DSA 전자 서명 사인과 검증
④ DSA 키 쌍 생성
⑤ DSA 키 변환
⑥ X.509 인증서 생성
⑦ Proprietary keystore 구현
⑧ DSA 알고리즘 매개변수
⑨ DSA 알고리즘 매개변수 생성
라) 암호 서비스 제공자 RSAJAC provider(com.sun.rsajca.Provider)
① RSA 키 쌍 생성
② RSA 키 변환
10) JCE
가) 주요 클래스와 인터페이스
① Cipher
② KeyAgreement
③ KeyGenerator
④ Mac
⑤ SecretKey
⑥ SecretKeyFactory
나) JCE 접근
KeyGenerator keyGenerator = KeyGenerator.getInstance(“Blowfish”);
Key key = keyGenerator.generatorKey();
Cipher cipher = Cipher.getInstance(“Blowfish/ECB/PKCS5Padding”);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = cipher.doFinal(myData);
다) JCE 설치
이름
BouncyCastle
URL
http://www.bouncycastle.org
12. JSSE
13. JAAS
http://docs.oracle.com/javase/7/docs/technotes/guides/security/jaas/JAASRefGuide.html
14. Java SASL
https://docs.oracle.com/javase/8/docs/technotes/guides/security/sasl/sasl-refguide.html
15. Java GSS-API
https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/tutorials/index.html
16. 커버로스
http://publib.boulder.ibm.com/html/as400/v5r1/ic2986/info/rzakh/rzakha06.htm
17. LDAP
http://jabcholove.tistory.com/89
18. 스프링에서의 보안
http://www.slideshare.net/madvirus/ss-36809454
19. AngularJS 에서의 보안
https://www.youtube.com/watch?v=18ifoT-Id54
20. 하둡에서의 보안
http://www.slideshare.net/oom65/hadoop-security-architecture
| SSH 인사이드 (0) | 2016.06.09 |
|---|---|
| HTTP 다이제스트 엑세스인증 (0) | 2015.09.20 |
| HTTP 기본인증 (Basic authentication) (0) | 2015.09.20 |
| HTTP 세션을 이용한 인증 (0) | 2015.06.04 |
| HTTPS 설정 및 사설인증서 관련 글들 (0) | 2015.06.04 |
| [ 하둡 인사이드 ] 5. 하둡 HDFS 쓰기 (0) | 2015.05.02 |
|---|---|
| [ 하둡 인사이드 ] 4. HDFS 읽기 (0) | 2015.05.02 |
| [ 하둡 인사이드 ] 2. Hadoop Streamming (0) | 2015.05.01 |
| hadoop-1.2.1 이클랩스 import 하기 (0) | 2015.04.27 |
| [ 하둡 인사이드 ] 1. Hadoop RPC (0) | 2015.04.27 |
hadoop-2.2.0 경우는 이클립스에서 maven 으로 import 하면 됩니다만
OS: | Ubuntu 12.04 | ||
JAVA version: | jdk 1.6.0_27 | ||
Eclipse version: | Service Release 1 |
1) download hadoop source code.
7) Test your environment
|
ubuntu의 기본 update repository에서는 sun-1.5-jdk를 제공하지 않으므로, 다음의 방법으로 추가 repository를 추가한다.
sudo add-apt-repository "deb http://us.archive.ubuntu.com/ubuntu/ hardy multiverse"
sudo add-apt-repository "deb http://us.archive.ubuntu.com/ubuntu/ hardy-updates multiverse"
aapt-get update
sudo apt-get install sun-java5-jdk
| [ 하둡 인사이드 ] 5. 하둡 HDFS 쓰기 (0) | 2015.05.02 |
|---|---|
| [ 하둡 인사이드 ] 4. HDFS 읽기 (0) | 2015.05.02 |
| [ 하둡 인사이드 ] 2. Hadoop Streamming (0) | 2015.05.01 |
| 하둡 쉘 스크립트 실행 순서도 | (0) | 2015.04.27 |
| [ 하둡 인사이드 ] 1. Hadoop RPC (0) | 2015.04.27 |
string guy = null;
for( Groups::iterator i = Groups.iterator(); i != Groups.end() ; ++i){
player p = *i;
if(p.id == 1){
guy = p.name;
}
}
return guy;player = Groups.findbyId(1);
if( player ){
return player.name;
}
elsle{
return null;
}fmap (getName) (findId 1) bool is_cool (const Thing& x) { ... }
find_if(begin, end, not1(ptr_fun(is_cool)));select * from player where id = 1 public Table select (Selector where){
Table resultTable = new ConcreteTable(null, columnNames.clone()};
Results currentRow = (Results) rows();
Cursor[] envelop = new Cursor[] { currentRow };
while(currentRow.advance(){
if(where.approve(envelope))
resultTable.insert( currentRow.cloneRow());
}
return new UnmodifiableTable(resultTable);
}struct table {
....
}
table t [][];
....
for(int i = 0 ; i < rows ; i++){
for( int j = 0 ; j < cols; j++){
...
}
}| 정규표현식 (Regex) 정리 (10) | 2015.07.23 |
|---|---|
| 주요 오픈소스 라이센스 (0) | 2015.06.26 |
| Actor 패턴 ? ActiveObject 패턴 ? with AKKA (0) | 2015.05.15 |
| 데브옵스(DevOps) 란 ? (0) | 2015.05.15 |
| 여러언어를 통해본 함수형 스타일 ( 함수포인터,함수자,람다 ) (0) | 2015.04.27 |
#include <stdio.h>
void apple(void)
{
printf("apple");
};
int main()
{
void (*fptr)(void); // 선언
fptr = apple; // 대입
fptr(); // 호출
someFunction(fptr); // 매개변수로 넘김.
}#include <iostream>
using namespace std;
class fruit
{
public:
void apple()
{
cout << "apple" << endl;
}
void berry()
{
cout << "berry" << endl;
}
};
int main()
{
fruit x, *y;
void (fruit::*f)(void); // 선언
f = &fruit::apple; // 대입
(x.*f)(); // 호출
f = &fruit::berry;
y = new fruit;
(y->*f)();
delete y;
} class CHello
{
void Say()
{
print(“hello”);
}
};
Void func1()
{
CHello hello; // CHello 의 객체 선언
boost::function< void ( void ) > memfunc; // boost::function 객체 선언
memfunc = boost::bind( &CHello::DebugOut, hello, _1 ); // DebugOut 함수를 func 에 바인딩
func2(memfunc);
}
Void func2(boost::function< void ( void ) > _func)
{
_func( 5 ); // CHello::Say() 가 호출!!! 1. 행위를 하게함. ( observer 패턴)
// 2. 호출위치를 조절할수도 있고
// 3. 다른모듈에서 CHello를 호출.(디펜던시문제)
}
#include <iostream>
#include <functional>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
auto f = bind(add, 1, 2);
cout << f() << "\n";
}
///////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <functional>
using namespace std;
using namespace std:placeholders;
int add(int a, int b) {
return a + b;
}
int main() {
auto add1 = bind(add, 1, _1);
cout << add1(100) << "\n";
}
boost::asio::ip::tcp::acceptor m_acceptor;
void handle_accept(Session* pSession, const boost::system::error_code& error)
{
if (!error)
{
std::cout << "클라이언트 접속 성공" << std::endl;
pSession->PostReceive();
}
}
m_acceptor.async_accept( m_pSession->Socket(),
boost::bind(&TCP_Server::handle_accept, // 함수 객체를 넘긴다. (함수포인터넘겨도됨)
this,
m_pSession,
boost::asio::placeholders::error)
);
boost::asio::ip::tcp::acceptor m_acceptor;
m_acceptor.async_accept( m_pSession->Socket(),
[this](boost::system::error_code error) // 람다식을 넘김!!
{
if (!error)
{
std::cout << "클라이언트 접속 성공" << std::endl;
m_pSession->PostReceive();
}
StartAccept();
}
);
Public void foo()
{
final int n = 1;
Class ActionListener()
{
Pubic void actionPerformed(Action e)
{
System.out.pringln(“Clicked! N =” +n);
}
}
ActionListener ac = new ActionListener()
Jbutton button = new Jbutton(“Click me”);
button.addActionListener(ac);
}
Public void foo()
{
final int n = 1;
Jbutton button = new Jbutton(“Click me”);
button.addActionListener(new ActionListener()
{
Pubic void actionPerformed(Action e)
{
System.out.pringln(“Clicked! N =” +n);
}
});
}
Public void foo() { final int n = 1; Jbutton button = new Jbutton(“Click me”); button.addActionListener( ()-> System.out.pringln(“Clicked! N =” +n);); }
//대리자 선언
public delegate void SayHandler(string mag);
[1]익명메서드 : Say 함수를 작성하지 않고 익명메서드로 작성
SayHandler hi = delegate(string msg)
{
Console.WriteLine(msg);
};
hi("익명메서드");
//[2]익명메서드 : Button의 click event를 익명 메서드로 작성
Button button = new Button();
button.Click += delegate(string msg)
{
Console.WriteLine(msg);
};
button.OnClick("이벤트 익명메서드");
//[3]람다표현식 : Button의 click event를 Ramda 표현식으로 작성
Button button1 = new Button();
button1.Click += (string msg) => Console.WriteLine(msg);
button.OnClick("람다 표현식");
스칼라에서 함수표현
def max(m: Int, n: Int): Int = if(m > n) m else n
스칼라에서의 람다식
1) 보통
def bubbleSort(arr: Array[Int], order: (Int, Int) => Boolean): Unit {
...
val o: Boolean = order(a, b)
...
}
val arr: Array[Int] = Array(2, 5, 1, 7, 8)
bubbleSort(arr, (a: Int, b: Int) => a > b)
2) 짧게
val arr = Array(2, 5, 1, 7, 8)
bubbleSort(arr, (a, b) => a > b)
3) 더 짧게
val arr = Array(2, 5, 1, 7, 8)
bubbleSort(arr, (_: Int) > (_: Int))
4) 가장 짧게
val arr = Array(2, 5, 1, 7, 8)
bubbleSort(arr, _ > _)
JAVA8 )
List names = Arrays.asList("1", "2", "3");
Stream lengths = names.stream().map(name -> name.length());
Scala )
val names = List("1", "2", "3")
val lengths = names.map(name => name.length)
JAVA8 )
List<Photo> photos = Arrays.asList(...)
List<Photo> output = photos.filter(p -> p.getSizeInKb() < 10)
Scala )
val photos = List(...)
val output = photos.filter(p => p.sizeKb < 10)function applyOperation(a, b, operation)
{
return operation(a,b);
}
function add(a,b) { return a+ b; }
applyOperation(1,2, add);
// anonymous inline function
applyOperation(4,7, function(a,b) {return a * b})class Array
def iterate!(code)
self.each_with_index do |n, i|
self[i] = code.call(n)
end
end
end
array = [1, 2, 3, 4]
array.iterate!(lambda { |n| n ** 2 })
puts array.inspect
# => [1, 4, 9, 16]
int count = 0;
for(String w : words){
if (w.length > 12 ) count++;
}long count = words.stream().filter( w -> w.length() > 12 ).count();long count = words.parallelStream().filter ( w -> w.length() > 12).count()| 정규표현식 (Regex) 정리 (10) | 2015.07.23 |
|---|---|
| 주요 오픈소스 라이센스 (0) | 2015.06.26 |
| Actor 패턴 ? ActiveObject 패턴 ? with AKKA (0) | 2015.05.15 |
| 데브옵스(DevOps) 란 ? (0) | 2015.05.15 |
| 언어에서 강력함 과 대중성 그리고 스칼라 (0) | 2015.04.27 |
public class TestServer implements RPCProtocol {
Class cls = Class.forName(“RPCProtocol“);
Class paramTypes[] = new Class[2];
pramTypes[0] = String.TYPE;
pramTypes[2] = Integer.TYPE;
Method meth = cls.getMethod(“heartbeat”, paramTypes);
Object arglist[] = new Object[2];
arglist[0] = new String(“hello world”)
arglist[1] = new Integer(2);
RPCProtocol rp = new TestServer ();
Object retObj = meth.invoke(rp, arglist);
Integer retval = (Integer) retObj;
중요포인트 ( 필요사항 ) : 실제 객체 / 클래스타입 / 메소드이름 / 인자타입 / 실제 인자 /
Hadoop 에서 각각에 대한 변수명
instance (실제객체)
protocol (클래스타입)
Invoocation ( 메소드이름, 인자클래스, 실제 인자값)
public class MyDebugInvocationHandler implements java.lang.reflect.InvocationHandler {
private Object target = null;
public void setTarget(Object target_) {
this.target = target_;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Going to execute method : " + method.getName);
Object retObject = method.invoke(target, args);
System.out.println("After execute method : " + method.getName());
return retObject;
}
}
-----------
IMyBusinessObject bo = new MyBusinessObject(); // 실제 비즈니스 객체
MyDebugInvocationHandler aMyDebugInvocationHandler = new MyDebugInvocationHandler();
aMyDebugInvocationHandler.setTarget(bo);
IMyBusinessObject proxyObject = (IMyBusinessObject) Proxy.newProxyInstance // 프록시 객체 생성
(IMyBusinessObject.class.getClassLoader(),
new Class[] { IMyBusinessObject.class }, // 프록시할 인터페이스
aMyDebugInvocationHandler); // InvocationHandler
// 프록시 객체 사용
System.out.println(proxyObject.doExecute("Hello World"));* InputStream / OutputStream
* Selctor
* Channel
* ByteBuffer
* Socket

DFSClient
(ClientProtocol)RPC.getProxy(ClientProtocol.class,
ClientProtocol.versionID, nameNodeAddr, ugi, conf,
NetUtils.getSocketFactory(conf, ClientProtocol.class), 0,..)
this.namenode = createNamenode(this.rpcNamenode, conf);
namenode.getBlockLocations(src, start, length);1)
final Invoker invoker = new Invoker(protocol, addr, ticket, conf, factory,
rpcTimeout, connectionRetryPolicy);
VersionedProtocol proxy = (VersionedProtocol)Proxy.newProxyInstance(
protocol.getClassLoader(), new Class[]{protocol}, invoker);
2)
private static class Invoker implements InvocationHandler {
private Client.ConnectionId remoteId;
private Client client;
private Invoker(Class<? extends VersionedProtocol> protocol,
InetSocketAddress address,
UserGroupInformation ticket,
Configuration conf,
SocketFactory factory,
int rpcTimeout,
RetryPolicy connectionRetryPolicy) throws IOException {
this.remoteId = Client.ConnectionId.getConnectionId(address, protocol,
ticket, rpcTimeout, connectionRetryPolicy, conf);
this.client = CLIENTS.getClient(conf, factory);
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
ObjectWritable value = (ObjectWritable)
client.call(new Invocation(method, args), remoteId);
return value.get();
}
public Writable call(Writable param, ConnectionId remoteId)
throws InterruptedException, IOException {
Call call = new Call(param);
Connection connection = getConnection(remoteId, call);
connection.sendParam(call); // send the parameter
public class NameNode implements ClientProtocol, DatanodeProtocol,
this.server = RPC.getServer(this, socAddr.getHostName(),
socAddr.getPort(), handlerCount, false, conf, namesystem
.getDelegationTokenSecretManager());public static Server getServer(...){
return new Server(instance, conf, bindAddress, port, numHandlers, verbose, secretManager);
}
public static class Server extends org.apache.hadoop.ipc.Server {
public Writable call(Class<?> protocol, Writable param, long receivedTime)
Invocation call = (Invocation)param;
if (verbose) log("Call: " + call);
Method method =
protocol.getMethod(call.getMethodName(),
call.getParameterClasses());
method.setAccessible(true);
long startTime = System.currentTimeMillis();
Object value = method.invoke(instance, call.getParameters());Server listener = new Listener();Listenervoid doAccept(SelectionKey key) Reader void doRead(SelectionKey key) Connection public int readAndProcess() private void processData(byte[] buf) Call call = new Call(id, param, this); callQueue.put(call); // queue the call; Handler final Call call = callQueue.take(); // pop the queue; value = call(call.connection.protocol, call.param, call.timestamp); Response
Invocation call = (Invocation)param;
Method method = protocol.getMethod(call.getMethodName(),call.getParameterClasses());
Object value = method.invoke(instance, call.getParameters());| [ 하둡 인사이드 ] 5. 하둡 HDFS 쓰기 (0) | 2015.05.02 |
|---|---|
| [ 하둡 인사이드 ] 4. HDFS 읽기 (0) | 2015.05.02 |
| [ 하둡 인사이드 ] 2. Hadoop Streamming (0) | 2015.05.01 |
| 하둡 쉘 스크립트 실행 순서도 | (0) | 2015.04.27 |
| hadoop-1.2.1 이클랩스 import 하기 (0) | 2015.04.27 |