# HG changeset patch # User Shinji KONO # Date 1261277061 -32400 # Node ID 226c97efb6930bbb1ea1fd2b0267d1a843ab2d45 # Parent 1bcc0070c2f603d795361001fab22861a086ee20# Parent dce00142f374233e8b56069809f0559bc1063290 merge diff -r 1bcc0070c2f6 -r 226c97efb693 .classpath --- a/.classpath Sat Feb 16 13:18:02 2008 +0900 +++ b/.classpath Sun Dec 20 11:44:21 2009 +0900 @@ -2,5 +2,6 @@ + diff -r 1bcc0070c2f6 -r 226c97efb693 .hgignore --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.hgignore Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,12 @@ +syntax: glob + +*.a +*.o +.*.swp +.*.swo +GTAGS +GRTAGS +GSYMS +GPATH + + diff -r 1bcc0070c2f6 -r 226c97efb693 .hgtags --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.hgtags Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,8 @@ +046feb56a196c8204fd2ca1d62f4ec492c057e39 metacomm-worked **INVALID** +1bcc0070c2f603d795361001fab22861a086ee20 tools +35375016b2f0ba3b13bd3376e3319903976a9bfe simple-test-passed +479c52c7de0b01e6c1a8bfd7d945056322501e83 before-distributed-select +7e0f6f00763e0a9366a741a6dd2f2a879d1cbc4b new-comdebug +fac6e0073b1a59d4089f51253c9812e69af208e2 meta-engine-written +fe338d497c728a94868b5eaa139053238f14f9a6 meta-comdebug-wokred +e457d6c8907a5485923b28ebaf5113cd80b2c6b8 FederatedLinda_test_two_connent diff -r 1bcc0070c2f6 -r 226c97efb693 .project --- a/.project Sat Feb 16 13:18:02 2008 +0900 +++ b/.project Sun Dec 20 11:44:21 2009 +0900 @@ -1,11 +1,16 @@ - FederatedLinda-Java + FederatedLinda + org.python.pydev.PyDevBuilder + + + + org.eclipse.jdt.core.javabuilder @@ -13,5 +18,6 @@ org.eclipse.jdt.core.javanature + org.python.pydev.pythonNature diff -r 1bcc0070c2f6 -r 226c97efb693 .pydevproject --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.pydevproject Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,6 @@ + + + + +python 2.5 + diff -r 1bcc0070c2f6 -r 226c97efb693 .settings/org.eclipse.jdt.core.prefs --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.settings/org.eclipse.jdt.core.prefs Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,12 @@ +#Tue Aug 19 14:22:01 JST 2008 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.5 diff -r 1bcc0070c2f6 -r 226c97efb693 build.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/build.xml Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff -r 1bcc0070c2f6 -r 226c97efb693 document/cls.graffle Binary file document/cls.graffle has changed diff -r 1bcc0070c2f6 -r 226c97efb693 document/connect.graffle Binary file document/connect.graffle has changed diff -r 1bcc0070c2f6 -r 226c97efb693 document/graphRing.png Binary file document/graphRing.png has changed diff -r 1bcc0070c2f6 -r 226c97efb693 document/metaRing.xls Binary file document/metaRing.xls has changed diff -r 1bcc0070c2f6 -r 226c97efb693 document/meta_ring_three.graffle Binary file document/meta_ring_three.graffle has changed diff -r 1bcc0070c2f6 -r 226c97efb693 document/metaengine.graffle Binary file document/metaengine.graffle has changed diff -r 1bcc0070c2f6 -r 226c97efb693 document/objring.xls Binary file document/objring.xls has changed diff -r 1bcc0070c2f6 -r 226c97efb693 document/resultTime.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/document/resultTime.txt Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,3 @@ +ServerStart2009/02/17 22:28:06.261 +TransferTime2009/02/17 22:28:09.538 +AroundTime2009/02/17 22:28:09.634 diff -r 1bcc0070c2f6 -r 226c97efb693 document/resultTime1024_0.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/document/resultTime1024_0.txt Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,3 @@ +ServerStart => 2009/02/18 14:34:34.413 +TransferTime => 2009/02/18 14:35:22.819 +AroundTime => null diff -r 1bcc0070c2f6 -r 226c97efb693 document/resultTime1024_2.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/document/resultTime1024_2.txt Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,4 @@ +ServerStart => 2009/02/19 22:51:24.021 +TransferTime => 2009/02/19 22:51:27.242 +AroundTime => 2009/02/19 22:51:27.364 +DiffTime => 121 diff -r 1bcc0070c2f6 -r 226c97efb693 document/resulttime.csv --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/document/resulttime.csv Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,1 @@ +,3,5,10,20,50,100 1024,0.277,0.447,0.961,2.606,9.092,16.192 3072,0.285,0.487,0.922,1.727,6.768,14.106 5120,0.269,0.474,0.897,1.757,6.911,14.276 10240,0.236,0.487,0.867,1.790,6.806,13.772 20480,0.314,0.502,0.923,1.730,6.643,14.169 51200,0.252,0.472,1.003,1.752,6.868,13.655 102400,0.394,0.437,0.913,2.180,6.716,14.701 512000,0.301,0.488,0.953,1.711,6.726,13.882 1024000,0.290,0.424,0.924,1.847,6.887,14.080 ,,,,,, ,,,,,, ,,,,,, ,,,,,, \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 document/ring_three.graffle Binary file document/ring_three.graffle has changed diff -r 1bcc0070c2f6 -r 226c97efb693 document/uml.graffle Binary file document/uml.graffle has changed diff -r 1bcc0070c2f6 -r 226c97efb693 examples/filesend/Makefile --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/filesend/Makefile Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,40 @@ +CC=gcc +CFLAGS=-g -O0 +CPPFLAGS=-I../../tools/Linda_library +LIBS=-llindaapi +LDFLAGS=-L../../tools/Linda_library + +TARGET=reader writer deleter + +all: $(TARGET) + +.c.o: + $(CC) $(CPPFLAGS) $(CFLAGS) -c $^ -o $@ + +reader: reader.o + $(CC) $(LDFLAGS) $^ $(LIBS) -o $@ +writer: writer.o + $(CC) $(LDFLAGS) $^ $(LIBS) -o $@ +deleter: deleter.o + $(CC) $(LDFLAGS) $^ $(LIBS) -o $@ + +run-server: + java -cp ../../FedLinda.jar fdl.FDLindaServ -port 10000 + +run-reader: reader + ./reader +run-writer: writer + ./writer + + +clean: + rm -rf *.o $(TARGET) + +makedata: + dd bs=1024 count=500 if=/dev/urandom of=testdata/test500K.dat + dd bs=1024 count=1000 if=/dev/urandom of=testdata/test1M.dat + dd bs=1024 count=5000 if=/dev/urandom of=testdata/test5M.dat + + + + diff -r 1bcc0070c2f6 -r 226c97efb693 examples/filesend/deleter.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/filesend/deleter.c Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,41 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "lindaapi.h" + +#define PORT 10000 + + +void +del_callback(unsigned char *data, void *arg) +{ + free(data); +} +void +psx_del(int t, int id) +{ + psx_callback_in(t, id, del_callback, NULL); +} + +int +main(int argc, char *argv[]) { + int len = 0; + int tspace; + int id = 10; + + init_linda(); + tspace = open_linda_java("localhost", PORT); + printf("open socket (tupple space id) = %d\n", tspace); + + psx_del(tspace, id); + + printf("mainLoop finished\n"); + exit(EXIT_SUCCESS); +} + + diff -r 1bcc0070c2f6 -r 226c97efb693 examples/filesend/reader.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/filesend/reader.c Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,60 @@ +#include +#include +#include +#include +#include +#include + +#include "lindaapi.h" + +#define PORT 10000 + +void +mainLoop(unsigned int tid, int read_id, FILE* out) +{ + unsigned int rd_seq; + unsigned char *tuple, *data; + int len; + + /* すでにデータが書き込まれた状態で動くこと */ + rd_seq = psx_rd(tid, read_id); + psx_sync_n(); + + while (1) { + int count; + tuple = psx_reply(rd_seq); + if (tuple) { + len = psx_get_datalength(tuple); + data = tuple+LINDA_HEADER_SIZE; + + count=0; + while (count +#include +#include +#include +#include +#include +#include + +#include "lindaapi.h" + +#define PORT 10000 + +#define SERIAL_REGIST_TUPLE_NO 1 + +void +mainLoop(int tid, int write_id, int fd) +{ + void *addr; + struct stat sb; + + if (fstat(fd, &sb) == -1) { + perror("fstat"); + exit(1); + } + addr = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (addr==NULL) { + perror("mmap"); + exit(1); + } + + printf("file size=%d\n", sb.st_size); + + psx_out(tid, write_id, addr, sb.st_size); + psx_sync_n(); + + return; +} + +int get_serial_id(int tid) { + char *data; + int serial; + int seq; + + seq = psx_in(tid, 65535); + do { + psx_sync_n(); + data = (char *)psx_reply(seq); + } while(data==0); + serial = atoi(data + LINDA_HEADER_SIZE); + psx_free(data); + + return serial; +} + +void send_serial_id(int tid, int serial_id) { + int safe_id = htonl(serial_id); + + psx_out(tid, SERIAL_REGIST_TUPLE_NO, (unsigned char *)&safe_id, sizeof(safe_id)); + psx_sync_n(); +} + +int +main(int argc, char *argv[]) { + int len = 0; + int tspace; + int serial; + int xml_id; + const char *linda_serv = "localhost"; + if (argc > 1) + linda_serv = argv[1]; + init_linda(); + tspace = open_linda_java(linda_serv, PORT); + printf("open socket (tupple space id) = %d\n", tspace); + serial = get_serial_id(tspace); + xml_id = serial * 10; + mainLoop(tspace, xml_id, fileno(stdin)); + sleep(1); + send_serial_id(tspace, serial); + printf("send xml_id = %d, seciral = %d\n",xml_id, serial); + exit(EXIT_SUCCESS); +} + +/* end */ diff -r 1bcc0070c2f6 -r 226c97efb693 examples/readerwriter/Makefile --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/readerwriter/Makefile Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,28 @@ +CC=gcc +CFLAGS=-g -O0 +CPPFLAGS=-I../../tools/Linda_library +LIBS=-llindaapi +LDFLAGS=-L../../tools/Linda_library + + +all: reader writer + +.c.o: + $(CC) $(CPPFLAGS) $(CFLAGS) -c $^ -o $@ + +reader: reader.o + $(CC) $(LDFLAGS) $^ $(LIBS) -o $@ +writer: writer.o + $(CC) $(LDFLAGS) $^ $(LIBS) -o $@ + +run-server: + java -cp ../../FedLinda.jar fdl.FDLindaServ -port 10000 + +run-reader: reader + ./reader +run-writer: writer + ./writer + + +clean: + rm -rf reader writer *.o diff -r 1bcc0070c2f6 -r 226c97efb693 examples/readerwriter/reader.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/readerwriter/reader.c Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,193 @@ +#include +#include +#include +#include +#include +#include + +#include "lindaapi.h" + +#define PORT 10000 + +/* + * lindaapiの例題 + * writer側で書き込んだ文字列を表示するだけ + * + * mainLoop: + * psx_rdを使った例題 + * 相手が追加で書き込まなければずっと同じものを読みつづける + * + * mainLoop2: + * psx_rdを使った例題 + * 上と違い、writerが送るフラグをみて、新しいデータだった場合のみ表示 + * + * mainLoop3: + * psx_wait_rdを使った例題 + * ビジーループでもないしフラグを見る必要もないwaitする + * + * mainLoop4: + * callback_wait_rdを使った例題 + * ループはsyncするだけよ + * + */ + +struct callback_arg{ + int tid; + int read_id; +}; +void +callbacker(unsigned char *tuple, void *arg) { + int len; + char *data; + struct callback_arg *carg = arg; + + len = psx_get_datalength(tuple); + // 最初の4byteデータは使わない + data = tuple+LINDA_HEADER_SIZE+4; + len -= 4; + + /* dataは'\0'で終わっている事を期待 (writerで保証する) */ + printf("get data[%d]: `%s'\n", len, data); + free(tuple); + + psx_callback_wait_rd(carg->tid, carg->read_id, callbacker, arg); +} +void +mainLoop4(int tid, int read_id) +{ + int rd_seq; + char *tuple, *data; + int len; + struct callback_arg carg = { tid, read_id }; + + psx_callback_wait_rd(tid, read_id, callbacker, &carg); + + while (1) { + psx_sync_n(); + usleep(500000); + } + + return; +} + +void +mainLoop3(int tid, int read_id) +{ + int rd_seq; + char *tuple, *data; + int len; + + while (1) { + rd_seq = psx_wait_rd(tid, read_id); + psx_sync_n(); + + while (1) { + tuple = psx_reply(rd_seq); + if (tuple) { + len = psx_get_datalength(tuple); + // 最初の4byteデータは使わない + data = tuple+LINDA_HEADER_SIZE+4; + len -= 4; + + /* dataは'\0'で終わっている事を期待 (writerで保証する) */ + printf("get data[%d]: `%s'\n", len, data); + free(tuple); + break; + } + psx_sync_n(); + usleep(500000); + } + } + + return; +} + +void +mainLoop2(int tid, int read_id) +{ + int rd_seq; + char *tuple, *data; + int len; + uint32_t prev_id=-1; + + while (1) { + rd_seq = psx_rd(tid, read_id); + psx_sync_n(); + + while (1) { + tuple = psx_reply(rd_seq); + if (tuple) { + uint32_t line_id; + len = psx_get_datalength(tuple); + // 最初の4byteデータは行番号 + data = tuple+LINDA_HEADER_SIZE+4; + len -= 4; + + line_id = ntohl(((uint32_t*)(tuple+LINDA_HEADER_SIZE))[0]); + if (prev_id!=line_id) { + /* dataは'\0'で終わっている事を期待 (writerで保証する) */ + printf("get data[%d]: `%s', line_id=%d\n", len, data, line_id); + prev_id = line_id; + } + + free(tuple); + break; + } + usleep(500000); + } + } + + return; +} + +void +mainLoop(int tid, int read_id) +{ + int rd_seq; + char *tuple, *data; + int len; + + while (1) { + rd_seq = psx_rd(tid, read_id); + psx_sync_n(); + + while (1) { + tuple = psx_reply(rd_seq); + if (tuple) { + len = psx_get_datalength(tuple); + // 最初の4byteデータは使わない + data = tuple+LINDA_HEADER_SIZE+4; + len -= 4; + + /* dataは'\0'で終わっている事を期待 (writerで保証する) */ + printf("get data[%d]: `%s'\n", len, data); + free(tuple); + break; + } + usleep(500000); + } + } + + return; +} + + +int +main(int argc, char *argv[]) { + int len = 0; + int tspace; + + init_linda(); + tspace = open_linda_java("localhost", PORT); + printf("open socket (tupple space id) = %d\n", tspace); + + mainLoop4(tspace, 10); + //mainLoop3(tspace, 10); + //mainLoop2(tspace, 10); + //mainLoop(tspace, 10); + + printf("mainLoop finished\n"); + exit(EXIT_SUCCESS); +} + + diff -r 1bcc0070c2f6 -r 226c97efb693 examples/readerwriter/writer.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/readerwriter/writer.c Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,86 @@ +#include +#include +#include +#include +#include +#include + +#include "lindaapi.h" + +#define PORT 10000 + +void +del_callback(unsigned char *data, void *arg) +{ + free(data); +} +void +psx_del(int t, int id) +{ + psx_callback_in(t, id, del_callback, NULL); +} + + +void +mainLoop(int tid, int write_id) +{ + int size=BUFSIZ; + char *buff = malloc(size); + int len; + uint32_t line_id=0; + + if ( (buff=malloc(size))==NULL ) { + perror("malloc"); + exit(EXIT_FAILURE); + } + + /* '\0'も含めて送信 */ + psx_out(tid, write_id, "\0\0\0\0aiueo", 10); + psx_sync_n(); + + while (1) { + char *data = buff+4; + /* 標準入力から読み込み、改行を削除 */ + fgets(data, size-4, stdin); + len = strlen(data); + if (data[len-1]=='\n') { + data[--len] = '\0'; + } + ((uint32_t*)buff)[0] = htonl(line_id); + + if (len==size) { + /* realloc */ + } + + /* まえのデータを消す */ + psx_del(tid, write_id); + /* '\0'も含めて送信 */ + psx_out(tid, write_id, (void *)buff, len+4+1); + + psx_sync_n(); + printf("send data[%d] line_id=%d, `%s'\n", len, line_id, data); + printf("line_id =%d\n", ntohl(((uint32_t*)buff)[0])); + + line_id++; + } + + return; +} + + +int +main(int argc, char *argv[]) { + int len = 0; + int tspace; + + init_linda(); + tspace = open_linda_java("localhost", PORT); + printf("open socket (tupple space id) = %d\n", tspace); + + mainLoop(tspace, 10); + + printf("mainLoop finished\n"); + exit(EXIT_SUCCESS); +} + + diff -r 1bcc0070c2f6 -r 226c97efb693 hostlist --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/hostlist Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,2 @@ +mcbk.cr.ie.u-ryukyu.ac.jp +mcbk.cr.ie.u-ryukyu.ac.jp diff -r 1bcc0070c2f6 -r 226c97efb693 nodelist --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nodelist Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,3 @@ +mcbk.cr.ie.u-ryukyu.ac.jp +cls001.cs.ie.u-ryukyu.ac.jp +cls002.cs.ie.u-ryukyu.ac.jp \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 nodelist.list --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nodelist.list Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,3 @@ +10000 +10001 +10002 \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 scripts-java/StartFDLindaServ2.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/scripts-java/StartFDLindaServ2.py Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,29 @@ +#! /usr/bin/env python +"""start process +""" +import pexpect +import re +import time +import sys +import os + +def main(base_port, ldserv_num): + + if not os.environ.has_key('LDSERV'): + ldserv = "java -classpath FedLinda.jar fdl.FDLindaServ" + else: + ldserv = os.environ['LDSERV'] + + for num in range(0,ldserv_num): + cmd = "".join([ldserv + ' -p ' + str(base_port+num) + ' &']) + os.system(cmd) + print 'start :', cmd + + +if __name__ == "__main__": + + if (len(sys.argv) != 3): + print 'Usage : %s ' % sys.argv[0] + sys.exit(1) + + main(int(sys.argv[1]), int(sys.argv[2])) diff -r 1bcc0070c2f6 -r 226c97efb693 scripts-java/pexpect.pyc Binary file scripts-java/pexpect.pyc has changed diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/AcceptHandler.java --- a/src/fdl/AcceptHandler.java Sat Feb 16 13:18:02 2008 +0900 +++ b/src/fdl/AcceptHandler.java Sun Dec 20 11:44:21 2009 +0900 @@ -1,75 +1,47 @@ package fdl; import java.io.IOException; -//import java.net.InetAddress; -//import java.net.InetSocketAddress; -//import java.net.UnknownHostException; -import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; -//import java.util.LinkedList; +import java.util.logging.Level; -public class AcceptHandler implements TupleHandler, PSXQueueInterface { - //public Hashtable tuple_space; - public Tuple[] tuple_space; +public class AcceptHandler implements TupleHandler { - public static int user = 0; - public byte userchar[] = new byte[2]; - public final int MAX_TUPLE = TupleHandler.MAX_TUPLE; - public Tuple tmpTuple; + public TupleSpace tupleSpace; + public ServerSocketChannel ss; + private FDLindaServ fds; - public AcceptHandler(Tuple[] _tuple_space) { + public AcceptHandler(FDLindaServ fds,ServerSocketChannel ss, TupleSpace tupleSpace) { // 読みこんだデータを格納するためのリストの初期化 - tuple_space = _tuple_space; + this.tupleSpace = tupleSpace; + this.ss = ss; + this.fds = fds; } public void handle(SelectionKey key) throws ClosedChannelException, IOException { ServerSocketChannel serverChannel - = (ServerSocketChannel)key.channel(); - + = (ServerSocketChannel)key.channel(); + + if (ss!=serverChannel) { + fds.log(Level.SEVERE,"Wrong server socket channel."); + } // アクセプト処理 SocketChannel channel = serverChannel.accept(); channel.configureBlocking(false); - System.out.println("Server: accepted "+channel.socket()); + fds.log(Level.INFO,"Server: accepted "+channel.socket()); - //初期生成 - if((tmpTuple = tuple_space[MAX_TUPLE-1]) == null) { - tmpTuple = tuple_space[MAX_TUPLE-1] = new Tuple(); - tmpTuple.next = null; - } else { - while(tmpTuple.next != null) tmpTuple = tmpTuple.next; - tmpTuple.next = new Tuple(); - tmpTuple = tmpTuple.next; - tmpTuple.next = null; - } - - user++; - - ByteBuffer data = ByteBuffer.allocate(2); - data.clear(); - userchar[0] = (byte) (user/10 + '0'); - userchar[1] = (byte) (user%10 + '0'); - - data.put(userchar[0]); - data.put(userchar[1]); - - data.rewind(); - tmpTuple.setData(data); - //Tuple - int id = MAX_TUPLE-1; - tmpTuple.setTuple('o', id, 0, data.limit(), data); - - - System.out.println("Server: assign id "+user); + // TCP N Delay を ServerSocketChannel のオプションに指定する + // setTcpNoDelay(boolean on) + tupleSpace.newUser(); // 入出力用のハンドラを生成し,アタッチする // 監視する操作は読み込みのみ - IOParam handler = new IOHandler(tuple_space); channel.register(key.selector(), SelectionKey.OP_READ, - handler); + new IOHandler(fds, tupleSpace,channel)); } + } diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/ByteBufferReader.java --- a/src/fdl/ByteBufferReader.java Sat Feb 16 13:18:02 2008 +0900 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,36 +0,0 @@ - -package fdl; - -import java.io.*; -import java.io.IOException; -import java.nio.*; - -public class ByteBufferReader extends Reader { - public ByteBuffer _buf; - - public ByteBufferReader(ByteBuffer buf) { - _buf = buf; - _buf.reset(); - } - - @Override - public int read(char[] cbuf, int off, int len) throws IOException { - // TODO Auto-generated method stub - for(int i=0;i Com_Hashtable = new Hashtable(); - public static LinkedList Report_Channellist = new LinkedList(); - - ComDebug(){ - - } - - public static void Report(LinkedList reportCh_list, ByteBuffer command, String report_txt) throws IOException { - //レポートするチャンネルが0ならreturn - if(reportCh_list.isEmpty()) { - return; - } - //dataをセット - ByteBuffer data = ByteBuffer.allocateDirect(24+(report_txt).length()*2); - data.clear(); // position = 0 - for(int i=0;i it = reportCh_list.iterator(); - while(it.hasNext()) { - io.send(it.next(), command, data); - } - } - private static String getRemoteHostAndPort(SocketChannel channel) { - String socketString = channel.socket().getRemoteSocketAddress().toString(); - String[] split = socketString.split("/"); - int length = split.length; - String hostAndPort = split[length-1]; - split = hostAndPort.split(":"); - String host = split[0]; - String port = split[1]; - int portnum = Integer.parseInt(port); - try { - InetSocketAddress address = new InetSocketAddress(InetAddress.getByName(host), portnum); - host = address.getHostName().toString(); - return (host +":"+port); - } - catch( UnknownHostException e ){ - return hostAndPort; - } - } - - private static String getLocalHostAndPort(SocketChannel channel) { - String socketString = channel.socket().getLocalSocketAddress().toString(); - String[] split = socketString.split("/"); - int length = split.length; - String hostAndPort = split[length-1]; - split = hostAndPort.split(":"); - String host = split[0]; - String port = split[1]; - try { - InetAddress localhost = InetAddress.getLocalHost(); - host = localhost.getHostName(); - return (host +":"+port); - } - catch( UnknownHostException e ){ - return (host +":"+port); - } - } - - public static String Com_inc(SelectionKey key, Hashtable comlist,int mode, int id, int seq, String sendtext) { - //通信ログ Hostname:port 'mode' =number 形式でインクリメント - int cnt = 0; - SocketChannel ch = (SocketChannel) key.channel(); - - String remoteString = getRemoteHostAndPort(ch); - String localString = getLocalHostAndPort(ch); - - String ComKey = localString + "--" + remoteString + " " + (char)mode; - if(comlist.containsKey(ComKey)){ - cnt = comlist.get(ComKey); - } - cnt++; - comlist.put(ComKey, cnt); - long time = System.currentTimeMillis(); - return (time+" "+ComKey+"="+cnt+" id="+id+" seq="+seq+" data="+sendtext); - } - - public static void addChannel(SelectionKey key, LinkedList reportCh_list) { - SocketChannel repch = (SocketChannel) key.channel(); - reportCh_list.add(repch); - } - - public static void delChannel(SelectionKey key, LinkedList reportCh_list) { - SocketChannel repch = (SocketChannel) key.channel(); - reportCh_list.remove(repch); - } - - - public void reportCh_remove(SelectionKey key, LinkedList reportCh_list) throws IOException { - //レポートチャンネルが0ならreturn - if(reportCh_list.isEmpty()) { - return; - }else { - System.out.println("ComDebug Report Channel remove :"+key.channel()); - delChannel(key,reportCh_list); - } - } - -} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/ComDebug_Client.java --- a/src/fdl/ComDebug_Client.java Sat Feb 16 13:18:02 2008 +0900 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,70 +0,0 @@ -package fdl; - - -import java.io.IOException; -//import java.nio.ByteBuffer; -//import java.nio.CharBuffer; -import java.nio.CharBuffer; - - -public class ComDebug_Client implements PSXQueueInterface{ - - static int id; - static final boolean debug = false; - - public static void main(String[] args) { - FederatedLinda fdl; - PSXLinda psx; - String host = "localhost"; - int port = 10000; - int connect_num = 1; - final String usages = "usage: ComDebug_Client [-h host -p port]"; - - //引数判定 - try { - if (args.length < 2) { - System.err.println(usages); - } - - for (int i=0; i"+r.toString()); - } - - System.out.println("COM_DEBUG Connected.["+host+":"+port+"]"); - psx.in(PRIVILEGED_ID_START+connect_num); - connect_num++; - while(true) { - fdl.sync_com(1000); - } - } catch (IOException nfex) { - nfex.printStackTrace(); - System.out.println("Faild."); - return; - } - } -} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/CommDebugHook.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/CommDebugHook.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,78 @@ +package fdl; + +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.util.LinkedList; + +public class CommDebugHook implements IOHandlerHook { + + public LinkedList logs = new LinkedList(); + // String conversion is too expensive, should use ByteBuffer directory or + // create log object for the purpose. + + public void closeHook(SelectionKey key) { + if (key!=null) logs.add(closeLog(key)); + } + + + public void checkHook(SelectionKey key, int id, int seq, char mode) { + if (isPrivilege(key, id)) return; + logs.add(log(key, id, seq, mode, null)); + } + + + public void inHook(SelectionKey key, int id, int seq, char mode) { + if (isPrivilege(key, id)) return; + logs.add(log(key, id, seq, mode, null)); + } + + + private boolean isPrivilege(SelectionKey key, int id) { + return key==null || id>=PSX.PRIVILEGED_ID_START; + } + + + public void outHook(SelectionKey key, int id, int seq, char mode, ByteBuffer data) { + if (isPrivilege(key, id)) return; + String sendtext = PSX.getdataString(data); + logs.add(log(key, id, seq, mode, sendtext)); + } + + + public void waitReadHook(SelectionKey key, int id, int seq, char mode) { + if (isPrivilege(key, id)) return; + logs.add(log(key, id, seq, mode, null)); + } + + public String log(SelectionKey key,int id, int seq,char mode, String sendtext) { + //通信ログ Hostname:port 'mode' =number 形式でインクリメント + int cnt = 0; + if (sendtext==null) sendtext="none"; + + IOHandler io = (IOHandler) key.attachment(); + String ComKey = io.localString + "--" + io.remoteString + " " + mode; + + io.cnt++; + long time = System.currentTimeMillis(); + return (time+" "+ComKey+"="+cnt+" id="+id+" seq="+seq+" data="+sendtext); + } + + private String closeLog(SelectionKey key) { + String close_Channel = key.channel().toString(); + String[] split = close_Channel.split("/"); + String local[] = split[1].split(" "); + String remote[] = split[2].split("]"); + + String localAddress = local[0]; + String remoteAddress = remote[0]; + + return "CloseInfo >"+localAddress+"--"+remoteAddress; + } + + public ByteBuffer getLog() { + String log = logs.poll(); + if (log==null) return null; + return PSX.string2ByteBuffer(log); + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/FDLindaServ.java --- a/src/fdl/FDLindaServ.java Sat Feb 16 13:18:02 2008 +0900 +++ b/src/fdl/FDLindaServ.java Sun Dec 20 11:44:21 2009 +0900 @@ -2,90 +2,113 @@ package fdl; import java.io.IOException; -import java.net.InetAddress; import java.net.InetSocketAddress; -//import java.nio.ByteOrder; +import java.net.SocketException; +import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; +import java.nio.channels.spi.AbstractSelector; import java.nio.channels.spi.SelectorProvider; import java.util.Iterator; +import java.util.logging.Level; -public class FDLindaServ implements PSXQueueInterface { + +public class FDLindaServ { static final int MAX_REQ = 1; static final int FAIL = (-1); - static final int MAX_UAER = 4; - static final int MAX_TUPLE = 65536; static final int DEF_PORT = 10000; - //public static final int TIMEOUT = 5*1000; - public static Tuple[] tuple_space; + public int port = DEF_PORT; + AbstractSelector selector; + private ServerSocketChannel ssChannel; + public TupleSpace tupleSpace; + public MetaEngine me; - @SuppressWarnings("unchecked") - public static void main(final String[] args) throws IOException { - @SuppressWarnings("unused") + public static void main(final String[] args) { final String usages = "usage: FDLindaServ [-p port]"; + int port = DEF_PORT; - //バイトオーダー確認 - //System.out.println(ByteOrder.nativeOrder().toString()); - - tuple_space = new Tuple[MAX_TUPLE]; - //引数判定 try { for (int i=0; i 0) { - @SuppressWarnings("unused") - int KeyCount = selector.select(); - // Iteratorを用意 - Iterator it = selector.selectedKeys().iterator(); - while (it.hasNext()) { - // SelectionKeyを取り出す - SelectionKey selKey = (SelectionKey)it.next(); - - // 操作に対する処理が行われていると認識させるためにremoveする - it.remove(); + ssChannel.configureBlocking(false); + this.log(Level.INFO,"Server: litening at "+ssChannel); + //セレクタにチャンネルを登録 + tupleSpace = new TupleSpace(this); + ssChannel.register(selector, SelectionKey.OP_ACCEPT, new AcceptHandler(this, ssChannel,tupleSpace)); + + + } - TupleHandler handler = (TupleHandler)selKey.attachment(); - handler.handle(selKey); - } - - } - } catch (IOException exc) { - exc.printStackTrace(); - } /*finally { - try { - for (SelectionKey key: selector.keys()) { - key.channel().close(); - } - } catch(IOException ex) { - ex.printStackTrace(); - }*/ - //} + public void checkTuple() { + checkTuple(0); + } + + public void checkTuple(long timeout) { + // セレクタによる監視 + try { + if (selector.select(timeout)>0) { +// this does not work because #it.remove() is not called. +// for(SelectionKey s:selector.selectedKeys()) { +// TupleHandler handler = (TupleHandler)s.attachment(); +// handler.handle(s); +// } + for (Iterator it = selector.selectedKeys().iterator();it.hasNext(); ) { + SelectionKey s = it.next(); + it.remove(); + TupleHandler handler = (TupleHandler)s.attachment(); + handler.handle(s); + } + } + } catch (ClosedChannelException e) { + // we have to do something... + } catch (IOException e) { + } + } + + + public void log(Level level,String msg) { + System.err.println(msg); + if (level==Level.SEVERE) + new IOException().setStackTrace(null); } } diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/FederatedLinda.java --- a/src/fdl/FederatedLinda.java Sat Feb 16 13:18:02 2008 +0900 +++ b/src/fdl/FederatedLinda.java Sun Dec 20 11:44:21 2009 +0900 @@ -14,15 +14,12 @@ import java.io.IOException; import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.CharBuffer; import java.nio.channels.ClosedSelectorException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; -import java.nio.channels.SocketChannel; import java.util.Hashtable; -import java.util.Set; - +import java.util.Iterator; +import java.util.logging.Level; /** FederatedLinda @@ -37,336 +34,156 @@ */ -public class FederatedLinda implements PSXQueueInterface { +public class FederatedLinda { - static FederatedLinda fdl; - static int MAX_SEQUENCE = 2048; - static boolean debug = true; + FederatedLinda fdl; + static int MAX_SEQUENCE = 2048; + static boolean debug = false; - public int tid; - public int seq; - public int qsize; - public PSXLinda linda; + public int tid; + public int seq; + public int qsize; + public PSXLinda linda; - public Selector selector; + public Selector selector; + + public PSXQueue q_top,q_end; + public PSXReply r_top,r_end; + public Hashtable seqHash; - public PSXQueue q_top,q_end; - public PSXReply r_top,r_end; - public Hashtable seqHash; + public static FederatedLinda init() { + FederatedLinda fdl = new FederatedLinda(); + return fdl; + } - static FederatedLinda init() - throws IOException { - if (fdl==null) { - fdl = new FederatedLinda(); + private FederatedLinda() { + try { + selector = Selector.open(); + } catch (IOException e) { + e.printStackTrace(); + } + seqHash = new Hashtable(); } - return fdl; - } - private FederatedLinda() + public PSXLinda open(String _host,int _port) + throws IOException { + tid++; + PSXLindaImpl newlinda = new PSXLindaImpl(this,selector,tid,_host,_port); + linda = newlinda.add(linda); + return linda; + } + + PSXLinda openFromMetaLinda(MetaLinda metaLinda, String _host, int _port) throws IOException { - selector = Selector.open(); - seqHash = new Hashtable(); - } - - public PSXLinda open(String _host,int _port) - throws IOException { - tid++; - // System.out.print("Tid = "); - // System.out.println(tid); - PSXLinda newlinda = new PSXLinda(this,tid,_host,_port); - linda = newlinda.add(linda); - return linda; - } - -/** - psx_queue (unsigned int tspace_id, unsigned int id, - unsigned int size, unsigned char *data, char mode, - void(*callback)(char*,void*), void * obj): - */ - - public PSXReply psx_queue(PSXLinda linda, int id, ByteBuffer s, int length, int mode, PSXCallback callback) { - PSXQueue c = new PSXQueue(linda,id,mode,s,length,callback); - - if (q_top == null) { - c = q_end = q_top = c; - } else { - q_end.next = c; - q_end = c; + tid++; + PSXLindaImpl newlinda = new PSXLindaImpl(this,metaLinda.fds.selector,tid,_host,_port); + linda = newlinda.add(linda); + return newlinda; } - qsize++; - if (mode != PSX_OUT) { - PSXReply p = new PSXReply(PSX_REPLY,callback); - p.seq = seq(p); - c.setSeq(p.seq); - if (debug) { - System.out.print("Integer compare="); - System.out.println((new Integer(2)).equals(new Integer(2))); - System.out.print("Seding seq="); - System.out.println(p.seq); - } - if (r_top == null){ - r_end = r_top = p; - } else { - r_end.next = p; - r_end = p; - } - return p; - } - return null; - } + public PSXReply psx_queue(PSXLinda linda, int id, ByteBuffer s, int mode, PSXCallback callback) { + PSXQueue c = new PSXQueue(linda,id,mode,s,callback); + + if (q_top == null) { + c = q_end = q_top = c; + } else { + q_end.next = c; + q_end = c; + } + qsize++; - public int seq(PSXReply reply) { - Integer s; - do { - seq++; - if (seq>MAX_SEQUENCE) { - seq = 0; - } - s = new Integer(seq); - } while (seqHash.containsKey(s)); - if (debug) { - System.out.print("hash value = "); - System.out.println(s.hashCode()); - } - seqHash.put(s,reply); - seq++; - return seq-1; - } - - public Selector selector() { - return selector; - } - - public int sync() throws IOException { - return sync(0); - } - - public int sync(long mtimeout) - throws IOException { - int key_num = 0; - Set keys; - - while (q_top != null){ - PSXQueue c = q_top; - c.Send(); - q_top = c.next; - // psx_free(c); - // q_top = c = t; - qsize--; + if (mode != PSX.PSX_OUT) { + PSXReply p = new PSXReply(PSX.PSX_REPLY,callback); + p.seq = seq(p); + c.setSeq(p.seq); + if (r_top == null){ + r_end = r_top = p; + } else { + r_end.next = p; + r_end = p; + } + return p; + } + return null; } - try { - key_num = selector.select(mtimeout); - keys = selector.selectedKeys(); - for (SelectionKey key : keys) { - // System.out.println("selecting"); - SocketChannel sock = (SocketChannel)key.channel(); - chkServe(sock); - } - } catch (IOException e) { - e.printStackTrace(); - } catch (ClosedSelectorException e) { - e.printStackTrace(); - } - - return key_num; - } - - public int sync_com(long mtimeout) - throws IOException { - int key_num = 0; - Set keys; - - while (q_top != null){ - PSXQueue c = q_top; - c.Send(); - q_top = c.next; - // psx_free(c); - // q_top = c = t; - qsize--; - } - - try { - key_num = selector.select(mtimeout); - keys = selector.selectedKeys(); - for (SelectionKey key : keys) { - SocketChannel sock = (SocketChannel)key.channel(); - chkCom(sock); - } - } catch (IOException e) { - e.printStackTrace(); - } catch (ClosedSelectorException e) { - e.printStackTrace(); - } - - return key_num; - } - -// should be in PSXLinda, but sock->linda is unknown here - - private void chkCom(SocketChannel sock) throws IOException { - - int length; - ByteBuffer command = ByteBuffer.allocate(LINDA_HEADER_SIZE); - command.order(ByteOrder.BIG_ENDIAN); - debug = false; - - sock.read(command); - command.rewind(); - length = command.getInt(LINDA_DATA_LENGTH_OFFSET); - if (length>0) { - ByteBuffer data = ByteBuffer.allocate(length); - int read = length; - if (debug) { - System.out.print("reading:"); - System.out.println(length); - } + public int seq(PSXReply reply) { + Integer s; + do { + seq++; + if (seq>MAX_SEQUENCE) { + seq = 0; + } + s = new Integer(seq); + } while (seqHash.containsKey(s)); + if (debug) { + log(Level.INFO,"hash value = "+s.hashCode()); + } + seqHash.put(s,reply); + seq++; + return seq-1; + } - data.order(ByteOrder.BIG_ENDIAN); - while(read>0) { - read -= sock.read(data); - } - data.rewind(); - - if (debug) { - char id = (char)command.getShort(LINDA_ID_OFFSET); - System.out.println("LENGTH:"+command.getInt(LINDA_PACKET_LENGTH_OFFSET)+" "+ - "MODE:"+(char)command.get(LINDA_MODE_OFFSET)+" "+ - "ID:"+(int)id+" "+ - "SEQ:"+command.getInt(LINDA_SEQ_OFFSET)+" "+ - "DATA LENGTH:"+command.getInt(LINDA_DATA_LENGTH_OFFSET)+" "); - System.out.println("DATA:"+data); - command.rewind(); - } - //if (debug_com) { - String comdata =""; - CharBuffer chardata = data.asCharBuffer(); - comdata = chardata.toString(); + public Selector selector() { + return selector; + } - //System.out.println("Com_data =>"); - System.out.println(comdata); - //} - /***if (debug) { - System.out.print("header:"); - for(int i=0;i0) { - ByteBuffer data = ByteBuffer.allocate(length); - int read = length; - if (debug) { - System.out.print("reading:"); - System.out.println(length); - } - - data.order(ByteOrder.BIG_ENDIAN); - while(read>0) { - read -= sock.read(data); - } - data.rewind(); + public int sync(long mtimeout) + throws IOException { + int key_num = 0; + queueExec(); - if (debug) { - char id = (char)command.getShort(LINDA_ID_OFFSET); - System.out.println("LENGTH:"+command.getInt(LINDA_PACKET_LENGTH_OFFSET)+" "+ - "MODE:"+(char)command.get(LINDA_MODE_OFFSET)+" "+ - "ID:"+(int)id+" "+ - "SEQ:"+command.getInt(LINDA_SEQ_OFFSET)+" "+ - "DATA LENGTH:"+command.getInt(LINDA_DATA_LENGTH_OFFSET)+" "); - System.out.println("DATA:"+data); - command.rewind(); - } - /***if (debug) { - System.out.print("header:"); - for(int i=0;i0) { - if(debug){ - System.out.print("reading command..."); - } - count = channel.read(command); - - if(count < 0) { - LinkedList reportCh_list = ComDebug.Report_Channellist; - ClosewishComDebug(key, command, reportCh_list); - readsize = -1; - return; - } - readsize -= count; - } - command.rewind(); - - int len = command.getInt(LINDA_PACKET_LENGTH_OFFSET); - int datalen = command.getInt(LINDA_DATA_LENGTH_OFFSET); - - ByteBuffer data = ByteBuffer.allocate(datalen); - int read = datalen; - - if (debug) { - System.out.println("reading: " +datalen); - } - - data.order(ByteOrder.BIG_ENDIAN); - data.clear(); - while(read>0) { - //System.out.print("reading2..."); - read -= channel.read(data); - } - data.rewind(); - - /* - static final int LINDA_PACKET_LENGTH_OFFSET =0; - static final int LINDA_MODE_OFFSET =0+4; - static final int LINDA_ID_OFFSET =1+4; - static final int LINDA_SEQ_OFFSET =3+4; - static final int LINDA_DATA_LENGTH_OFFSET =7+4; - static final int LINDA_HEADER_SIZE =12+4; - */ - command.order(ByteOrder.BIG_ENDIAN); - command.rewind(); - - /*** print data ***/ - char id = (char)command.getShort(LINDA_ID_OFFSET); - System.out.println("LENGTH:"+command.getInt(LINDA_PACKET_LENGTH_OFFSET)+" "+ - "MODE:"+(char)command.get(LINDA_MODE_OFFSET)+" "+ - "ID:"+(int)id+" "+ - "SEQ:"+command.getInt(LINDA_SEQ_OFFSET)+" "); - //"SEQ:"+command.getInt(LINDA_SEQ_OFFSET)+" "+ - //"DATA LENGTH:"+command.getInt(LINDA_DATA_LENGTH_OFFSET)+" "); - //System.out.println("DATA:"+data); - //データ処理 - command.rewind(); - manager_run(key, command, data, len); - - key.interestOps(key.interestOps() | SelectionKey.OP_READ ); + public void handle(SelectionKey key) { + // 書き込み可であれば,読み込みを行う + if (key.isReadable()) { + try { + SocketChannel channel = (SocketChannel)key.channel(); + if (ch!=channel) { + fds.log(Level.INFO,"Wrong socket on IOHandler"); + } + // 読み込み用のバッファの生成 + ByteBuffer command = ByteBuffer.allocate(PSX.LINDA_HEADER_SIZE); + command.order(ByteOrder.BIG_ENDIAN); + ByteBuffer data = PSX.receivePacket(channel,command); + manager_run(key, command, data); + } catch (ClosedChannelException e) { + key.cancel(); + tupleSpace.hook.closeHook(key); + } catch (IOException e) { + key.cancel(); + tupleSpace.hook.closeHook(key); + } + } } - - public void manager_run(SelectionKey key, ByteBuffer command, ByteBuffer data, int len) throws IOException { - command.order(ByteOrder.BIG_ENDIAN); - int mode = command.get(LINDA_MODE_OFFSET); - char idc = (char)command.getShort(LINDA_ID_OFFSET); - int id = (int)idc; - int seq = command.getInt(LINDA_SEQ_OFFSET); + public void manager_run(SelectionKey key, ByteBuffer command, ByteBuffer data) throws IOException { + command.order(ByteOrder.BIG_ENDIAN); + int mode = command.get(PSX.LINDA_MODE_OFFSET); command.rewind(); - String sendtext = "none"; - - - com_debug = new ComDebug(); - Hashtable com_Loggingtable = ComDebug.Com_Hashtable; - LinkedList reportCh_list = ComDebug.Report_Channellist; - + if (debug) { - System.out.println("data from : "+key.channel()); + fds.log(Level.INFO,"data from : "+key.channel()); } - if((mode == '!') || (len == 0)) { - ClosewishComDebug(key, command, reportCh_list); - } - else if(mode == PSX_CHECK) { - sendtext = Check(key, command); + if(mode == '!') { + tupleSpace.hook.closeHook(key); + } else if(mode == PSX.PSX_CHECK) { + tupleSpace.Check(key, command); + } else if(mode == PSX.PSX_IN || mode == PSX.PSX_RD){ + tupleSpace.In_Rd(key, command, mode); + } else if (mode == PSX.PSX_WAIT_RD) { + tupleSpace.Wait_Rd(key, command, mode); + } else if(mode == PSX.PSX_OUT) { + tupleSpace.Out(key, command, data); + } else { + tupleSpace.hook.closeHook(key); + fds.log(Level.SEVERE,"Incorrect tuple operation"); } - else if(mode == PSX_IN || mode == PSX_RD){ - sendtext = In_Rd(key, command, mode); - } else if (mode == PSX_WAIT_RD) { - Wait_Rd(key, command, mode); - } else if(mode == PSX_OUT) { - sendtext = Out(command, data); - } else { - System.out.println("Uncorrect buffer"); - System.exit(1); - } - - //COM_DEBUG - if(id > PRIVILEGED_ID_START && id < PRIVILEGED_ID_END){ - ComDebug.addChannel(key, reportCh_list); - } - //DEBUG用カウンタ - String debug_rep = ComDebug.Com_inc(key, com_Loggingtable, mode, id, seq, sendtext); - //DEBUG用レポート - ComDebug.Report(reportCh_list, command, debug_rep); - - if (key.interestOps() - != (SelectionKey.OP_READ)) { - // 読み込み操作に対する監視を行う - key.interestOps(SelectionKey.OP_READ ); - } } - private void ClosewishComDebug(SelectionKey key, ByteBuffer command, - LinkedList reportCh_list) throws IOException { - String close_Channel = key.channel().toString(); - String[] split = close_Channel.split("/"); - String local[] = split[1].split(" "); - String remote[] = split[2].split("]"); - - String localAddress = local[0]; - String remoteAddress = remote[0]; - - Connection_Close(key); - com_debug.reportCh_remove(key, reportCh_list); - ComDebug.Report(reportCh_list, command, "CloseInfo >"+localAddress+"--"+remoteAddress); - } - - private void Connection_Close(SelectionKey key) throws IOException { - System.out.println("Connection closed by "+key.channel()); + void Connection_Close(SelectionKey key) throws IOException { + fds.log(Level.INFO,"Connection closed by "+key.channel()); SocketChannel channel = (SocketChannel)key.channel(); key.cancel(); channel.close(); } + } diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/IOHandlerHook.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/IOHandlerHook.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,16 @@ +package fdl; + +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; + +public interface IOHandlerHook { + void closeHook(SelectionKey key); + + void inHook(SelectionKey key, int id, int seq, char mode); + + void outHook(SelectionKey key, int id, int seq, char mode, ByteBuffer data); + + void waitReadHook(SelectionKey key, int id, int seq, char mode); + + void checkHook(SelectionKey key, int id, int seq, char mode); +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/IOParam.java --- a/src/fdl/IOParam.java Sat Feb 16 13:18:02 2008 +0900 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,353 +0,0 @@ -package fdl; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.SelectionKey; -import java.nio.channels.SocketChannel; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; - -public class IOParam implements TupleHandler, PSXQueueInterface{ - static final boolean debug = true; - static final int CAPSIZE = 4194304; - public Tuple[] tuple_space; - - public IOParam(Tuple[] _tuple_space) { - super(); - // 読みこんだデータを格納するためのリストの初期化 - tuple_space = _tuple_space; - } - - public IOParam() { - // TODO Auto-generated constructor stub - } - - protected String Out(ByteBuffer command, ByteBuffer data) throws IOException { - Tuple tmpTuple; - int id; - int datasize; - char idc = (char)command.getShort(LINDA_ID_OFFSET); - command.rewind(); - id = (int)idc; - String sendtext = "none"; - - datasize = command.getInt(LINDA_DATA_LENGTH_OFFSET); - command.rewind(); - - System.out.println("*** out command : id = "+id +" ***"); - - while((tuple_space[id] != null) && - ((tuple_space[id].mode == PSX_WAIT_RD)||(tuple_space[id].mode == PSX_RD))) { - command.put(LINDA_MODE_OFFSET, (byte)'a'); - command.rewind(); - command.putInt(LINDA_SEQ_OFFSET, tuple_space[id].getSeq()); - command.rewind(); - //if(debug){ - //int sendsize = tmpTuple.getdataLength()+LINDA_HEADER_SIZE; - //System.out.println("send size "+sendsize+" : mode = "+(char)mode); - //} - //ByteBuffer sendcommand = tmpTuple.getCommand(); - //ByteBuffer senddata = tmpTuple.getData(); - send(tuple_space[id].ch, command, data); - - sendtext = getdataString(data); - - - //後処理 - tmpTuple = tuple_space[id]; - tuple_space[id] = tmpTuple.next; - tmpTuple = null; - } - if(tuple_space[id] != null && tuple_space[id].mode == PSX_IN) { - command.put(LINDA_MODE_OFFSET, (byte)'a'); - command.rewind(); - command.putInt(LINDA_SEQ_OFFSET, tuple_space[id].getSeq()); - command.rewind(); - - if(debug){ - int sendsize = datasize+LINDA_HEADER_SIZE; - System.out.println("send size "+sendsize+" : mode = "+(char)'a'); - } - //ByteBuffer sendcommand = tmpTuple.getCommand(); - //ByteBuffer senddata = tmpTuple.getData(); - send(tuple_space[id].ch, command, data); - - sendtext = getdataString(data); - - //後処理 - tmpTuple = tuple_space[id]; - tuple_space[id] = tmpTuple.next; - tmpTuple = null; - } else if ((tuple_space[id] == null)|| (tuple_space[id].getMode() == PSX_OUT)) { - if((tmpTuple = tuple_space[id]) == null) { - tmpTuple = tuple_space[id] = new Tuple(); - tmpTuple.next = null; - } - else { - while(tmpTuple.next != null) tmpTuple = tmpTuple.next; - tmpTuple.next = new Tuple(); - tmpTuple = tmpTuple.next; - tmpTuple.next = null; - } - - tmpTuple.setMode('o'); - int seq = command.getInt(LINDA_SEQ_OFFSET); - command.rewind(); - tmpTuple.setSeq(seq); - tmpTuple.setData(data); - tmpTuple.setDataLength(datasize); - if(debug){ - System.out.println("data inserted len = "+tmpTuple.getdataLength()+" : id = "+id); - } - } - else { - System.out.println("Uncorrect mode :"+(char)tuple_space[id].getMode()); - command.clear(); - data.clear(); - System.exit(1); - } - return sendtext; - } - - protected void Wait_Rd(SelectionKey key, ByteBuffer command, int mode) { - Tuple tmpTuple; - int id; - - char idc = (char)command.getShort(LINDA_ID_OFFSET); - command.rewind(); - id = (int)idc; - - System.out.println("*** "+(char)mode+" command : id = "+ id +" ***\n"); - - tmpTuple = new Tuple(); - tmpTuple.setMode(mode); - int seq = command.getInt(LINDA_SEQ_OFFSET); - command.rewind(); - tmpTuple.setSeq(seq); - tmpTuple.ch = (SocketChannel) key.channel(); - tmpTuple.setDataLength(0); - ByteBuffer buff = ByteBuffer.allocate(0); - tmpTuple.setData(buff); - tmpTuple.next = tuple_space[id]; - tuple_space[id] = tmpTuple; - if(debug){ - System.out.println("data inserted insert seq = "+seq +", id = "+id); - } - } - - protected String In_Rd(SelectionKey key, ByteBuffer command, int mode) - throws IOException { - Tuple tmpTuple; - int id; - //id = command.getInt(LINDA_ID_OFFSET); - //int mode = command.getInt(LINDA_MODE_OFFSET); - Tuple temp = null; - - char idc = (char)command.getShort(LINDA_ID_OFFSET); - command.rewind(); - id = (int)idc; - - String sendtext = "none"; - - System.out.println("*** "+(char)mode+" command : id = "+ id +" ***\n"); - - tmpTuple = tuple_space[id]; - - //wを無視 - while(tmpTuple != null && tmpTuple.next != null && (tmpTuple.mode == 'w')){ - temp = tmpTuple; - tmpTuple = tmpTuple.next; - } - - if (tmpTuple != null && (tmpTuple.mode == 'o')){ - //tmpTuple = new Tuple((SocketChannel)key.channel()); - int seq = command.getInt(LINDA_SEQ_OFFSET); - command.rewind(); - tmpTuple.setCommand('a', seq); - - if(debug){ - int sendsize = tmpTuple.getdataLength()+LINDA_HEADER_SIZE; - System.out.println("send size "+sendsize+" : mode = "+(char)tmpTuple.getMode()); - } - - //send - ByteBuffer sendcommand = tmpTuple.getCommand(); - ByteBuffer senddata = tmpTuple.getData(); - send(key,sendcommand, senddata); - - sendtext = getdataString(senddata); - - - //INの場合はremoveする - if(mode == PSX_IN) { - if(tmpTuple.data != null){ - //ByteBuffer buff = ByteBuffer.allocate(0); - //tmpTuple.setData(buff); - tmpTuple.data = null; - } - if(temp != null){ - temp.next = tmpTuple.next; - } - else { - tuple_space[id] = tmpTuple.next; - } - tmpTuple = null; - } - } else { - if(tmpTuple == null) { - //ServerSocketChannel sc = (ServerSocketChannel)key.channel(); - tmpTuple = tuple_space[id] = new Tuple((SocketChannel)key.channel()); - tmpTuple.next = null; - }else { - while(tmpTuple.next !=null) tmpTuple =tmpTuple.next; - tmpTuple.next= new Tuple((SocketChannel)key.channel()); - tmpTuple = tmpTuple.next; - tmpTuple.next = null; - } - - tmpTuple.setMode(mode); - int seq2 = command.getInt(LINDA_SEQ_OFFSET); - command.rewind(); - tmpTuple.setSeq(seq2); - tmpTuple.ch = (SocketChannel) key.channel(); - tmpTuple.setDataLength(0); - ByteBuffer buff = ByteBuffer.allocate(0); - buff.rewind(); - tmpTuple.setData(buff); - - if(debug){ - System.out.println("data inserted insert seq = "+seq2 +", id = "+id); - } - } - - //} else if (command.getInt(LINDA_MODE_OFFSET) == PSX_WAIT_RD) { - return sendtext; - } - - protected String Check(SelectionKey key, ByteBuffer command) throws IOException { - ByteBuffer data; - Tuple tmpTuple; - int id; - char idc = (char)command.getShort(LINDA_ID_OFFSET); - command.rewind(); - id = (int)idc; - String sendtext = "none"; - - tmpTuple = tuple_space[id]; - while(tmpTuple != null && tmpTuple.next != null && (tmpTuple.mode == 'w')){ - tmpTuple = tmpTuple.next; - } - if (tmpTuple != null && (tmpTuple.mode == 'o')) { - command.putInt(LINDA_DATA_LENGTH_OFFSET, tmpTuple.datalen); - command.rewind(); - data = tmpTuple.getData(); - }else { - //means no out tuple - command.putInt(LINDA_DATA_LENGTH_OFFSET, 0); - command.rewind(); - data = null; - data = ByteBuffer.allocate(0); - } - send(key, command, data); - - sendtext = getdataString(data); - - return sendtext; - } - - public void send(SocketChannel ch, ByteBuffer command, ByteBuffer data) - throws IOException { - if (debug) { - if (command == null) { - System.out.println("Manager_run: command is null"); - } - if (data == null) { - System.out.println("Manager_run: data is null"); - } - } - int send_size = LINDA_HEADER_SIZE; - int count = 0; - - //command Send - command.rewind(); - while(send_size > 0){ - count = ch.write(command); - if(count < 0){ - System.out.println("Write Falied! close ch:"+ch); - ch.close(); - return; - } - send_size -= count; - } - - //data Send - data.rewind(); - if(data != null) { - data.rewind(); - ch.write(data); - } - } - - public void send(SelectionKey key, ByteBuffer command, ByteBuffer data) - throws IOException { - SocketChannel ch = (SocketChannel)key.channel(); - if (debug) { - if (command == null) { - System.out.println("Manager_run: command is null"); - } - if (data == null) { - System.out.println("Manager_run: data is null"); - } - } - int send_size = LINDA_HEADER_SIZE; - int count = 0; - - //command Send - command.rewind(); - while(send_size > 0){ - count = ch.write(command); - if(count < 0){ - System.out.println("Write Falied! close ch:"+ch); - ch.close(); - return; - } - send_size -= count; - } - - //data Send - data.rewind(); - if(data != null) { - data.rewind(); - ch.write(data); - } - } - - private String getdataString(ByteBuffer data) { - String sendtext; - data.rewind(); - //set sendtext - //CharBuffer chardata = data.asCharBuffer(); - - //Decode UTF-8 to System Encoding(UTF-16) - Charset charset = Charset.forName("UTF-8"); - CharsetDecoder decoder = charset.newDecoder(); - CharBuffer cb = null; - try { - cb = decoder.decode(data); - } catch (CharacterCodingException e) { - e.printStackTrace(); - } - cb.rewind(); - - sendtext = cb.toString(); - return sendtext; - } - - public void handle(SelectionKey key) throws ClosedChannelException, - IOException { - - } -} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/MetaEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/MetaEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,5 @@ +package fdl; + +public interface MetaEngine { + void mainLoop(); +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/MetaLinda.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/MetaLinda.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,139 @@ + +/* + * @(#)MetaLinda.java 1.1 06/04/01 + * + * Copyright 2008 Shinji KONO + * + + Meta Lidna + Trasport layer of Meta Linda API + + */ + +package fdl; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.LinkedList; + +/** + MetaLinda + * + * @author Shinji Kono + * + + meta tuple interface in Linda Server + + */ + +public class MetaLinda implements PSXLinda { + + public TupleSpace ts; + public FDLindaServ fds; + public FederatedLinda fdl=FederatedLinda.init(); + public PSXLinda next=null; + private LinkedList replies=new LinkedList(); + + public MetaLinda(TupleSpace ts,FDLindaServ fds) { + this.ts = ts; + this.fds = fds; + } + + public PSXLinda open(String _host,int _port) + throws IOException { + return fdl.openFromMetaLinda(this, _host, _port); + } + + public PSXReply in(int id) { + MetaReply r = new MetaReply(PSX.PSX_IN,id,ts); + addReply(r); + return r; + } + + public void in(int id, PSXCallback callback) { + MetaReply r = new MetaReply(PSX.PSX_IN,id,ts, callback); + addReply(r); + } + + private void addReply(MetaReply r) { + replies.addLast(r); + } + + public PSXReply ck(int id) { + MetaReply r = new MetaReply(PSX.PSX_CHECK,id,ts); + return r; + } + + public void ck(int id, PSXCallback callback) { + MetaReply r = new MetaReply(PSX.PSX_CHECK,id,ts,callback); + addReply(r); + } + + public PSXReply out(int id, ByteBuffer data) { + MetaReply r = new MetaReply(PSX.PSX_OUT,id,ts,data,null); + addReply(r); + return r; + } + + public PSXReply update(int id, ByteBuffer data) { + MetaReply r = new MetaReply(PSX.PSX_UPDATE,id,ts,data,null); + return r; + } + + public void update(int id, ByteBuffer data,PSXCallback callback) { + MetaReply r = new MetaReply(PSX.PSX_UPDATE,id,ts,data,callback); + addReply(r); + } + + public PSXReply rd(int id) { + MetaReply r = new MetaReply(PSX.PSX_RD,id,ts); + return r; + } + + public void rd(int id, PSXCallback callback) { + MetaReply r = new MetaReply(PSX.PSX_RD,id,ts,callback); + addReply(r); + } + + public PSXLinda add(PSXLinda linda) { + next = linda; + return this; + } + + + public int sync() { + return sync(0); + } + + public int sync(long timeout) { + fds.checkTuple(timeout); // fdl sync is also handled here + /* + * r.callback() may call meta.sync() and modifies the + * replies queue. Do current size of queue only. The + * rest is checked on the next sync call including + * the recursive case. + */ + int count = replies.size(); + while(count-->0) { + MetaReply r = replies.poll(); + // previous call back may call this sync and make + // replies shorter. + if (r==null) break; + if (r.ready()) { + } else { + addReply(r); + } + } + return 0; + } + + public void send(ByteBuffer command, ByteBuffer data) { + } + + public void setTupleSpaceHook(IOHandlerHook hook) { + ts.hook = hook; + } +} + + +/* end */ diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/MetaLogEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/MetaLogEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,46 @@ +package fdl; + +import java.nio.ByteBuffer; + +/** + * @author kono + * Meta Protocol Engine for each Linda Server + */ + +public class MetaLogEngine implements MetaEngine { + MetaLinda meta; + boolean running = true; + CommDebugHook commDebug; + + public MetaLogEngine(MetaLinda meta) { + this.meta = meta; + } + + PSXCallback monitor_callback_start = + new PSXCallback() {public void callback(ByteBuffer reply) { + meta.setTupleSpaceHook(commDebug = new CommDebugHook()); + meta.out(PSX.META_MONITOR_DATA, null); + meta.in(PSX.META_MONITOR,monitor_callback); + }}; + PSXCallback monitor_callback = + new PSXCallback() {public void callback(ByteBuffer reply) { + ByteBuffer data; + do { + data = commDebug.getLog(); + if (data!=null) break; + meta.sync(); + } while (running); + if (running) { + meta.out(PSX.META_MONITOR_DATA, data); + meta.in(PSX.META_MONITOR,monitor_callback); + } + }}; + + public void mainLoop() { + meta.in(PSX.META_MONITOR,monitor_callback_start); + meta.in(PSX.META_STOP, new PSXCallback() {public void callback(ByteBuffer reply) { + running = false;}}); + while(running) + meta.sync(); + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/MetaReply.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/MetaReply.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,61 @@ +package fdl; + +import java.nio.ByteBuffer; + +public class MetaReply extends PSXReply { + + public int id; + public TupleSpace ts; + + public MetaReply(int mode, int id,TupleSpace ts) { + this.mode = mode; + this.id = id; + this.ts = ts; + this.command = ByteBuffer.allocate(PSX.LINDA_HEADER_SIZE); + } + + public MetaReply(int mode, int id, TupleSpace ts,PSXCallback callback) { + this(mode,id,ts); + this.callback = callback; + } + + public MetaReply(int mode, int id, TupleSpace ts,ByteBuffer data, + PSXCallback callback) { + this(mode,id,ts); + this.data = data; + this.callback = callback; + } + + void checkTuple() { + ByteBuffer data = ts.IN(id, mode, command); + if (data!=null) { + this.data = data; + mode = PSX.PSX_ANSWER; + if (callback!=null) callback.callback(data); + } + } + + public boolean ready() { + switch(mode) { + case PSX.PSX_IN: + case PSX.PSX_RD: + checkTuple(); + break; + case PSX.PSX_CHECK: + data = ts.check1(null, command); + if (data!=null) { + mode = PSX.PSX_ANSWER; + } + break; + case PSX.PSX_OUT: + command=PSX.setCommand(PSX.PSX_OUT, id, 0, data); + ts.Out(null, command, data); + return true; + case PSX.PSX_UPDATE: + // not implemented + break; + } + return mode==PSX.PSX_ANSWER; + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/NullIOHandlerHook.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/NullIOHandlerHook.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,25 @@ +package fdl; + +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; + +public class NullIOHandlerHook implements IOHandlerHook { + + public void checkHook(SelectionKey key, int id, int seq, char mode) { + } + + public void closeHook(SelectionKey key) { + } + + public void inHook(SelectionKey key, int id, int seq, char mode) { + } + + public void outHook(SelectionKey key, int id, int seq, char mode, + ByteBuffer data) { + } + + public void waitReadHook(SelectionKey key, int id, int seq, char mode) { + } + + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/NullMetaEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/NullMetaEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,19 @@ +package fdl; + +import java.nio.ByteBuffer; + +public class NullMetaEngine implements MetaEngine { + public MetaLinda meta; + public boolean running=true; + + public NullMetaEngine(MetaLinda meta) { + this.meta = meta; + } + + public void mainLoop() { + meta.in(PSX.META_STOP, new PSXCallback() {public void callback(ByteBuffer reply) { + running = false;}}); + while(running) + meta.sync(); + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/PSX.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/PSX.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,265 @@ + +/* + * @(#)PSXQueueInterface.java 1.1 06/04/01 + * + * Copyright 2006 Shinji KONO + * + + PSX Lidna + Trasport layer of PSX Linda library + + */ + +package fdl; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.CharBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.SocketChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; + + + +/** + PSX Tuple Command Protocol Format + + All PSX offset command operation should be here. + Some public library + */ + +public class PSX { + static final int PSX_IN = 'i'; + static final int PSX_OUT = 'o'; + static final int PSX_UPDATE = 'u'; + static final int PSX_RD = 'r'; + static final int PSX_CHECK = 'c'; + static final int PSX_REPLY = '?'; + static final int PSX_WAIT_RD = 'w'; + static final int PSX_ANSWER = 'a'; + static final int PSX_HTTP_ANSWER = 'P'; // Put + static final int PSX_HTTP_REQUEST = 'G'; // Get + static final int PSX_COM_DEBUG = 'D'; //Communication DEBUG + + static final int LINDA_PACKET_LENGTH_OFFSET =0; + static final int LINDA_MODE_OFFSET =0+4; + static final int LINDA_ID_OFFSET =1+4; + static final int LINDA_SEQ_OFFSET =3+4; + static final int LINDA_DATA_LENGTH_OFFSET =7+4; + static final int LINDA_HEADER_SIZE =12+4; + static final int INT_SIZE =4; + static final int SHORT_SIZE =2; + + static final int PRIVILEGED_ID_START = 32768; + static final int PRIVILEGED_ID_END = 36864; + static public final int META_STOP = PRIVILEGED_ID_START; + static public final int META_MONITOR = PRIVILEGED_ID_START+1; + static public final int META_MONITOR_DATA = PRIVILEGED_ID_START+2; + + + static void printCommand(String comment, ByteBuffer command, ByteBuffer data) { + char id = (char)command.getShort(LINDA_ID_OFFSET); + System.err.println(comment+" LENGTH:"+command.getInt(LINDA_PACKET_LENGTH_OFFSET)+" "+ + "MODE:"+(char)command.get(LINDA_MODE_OFFSET)+" "+ + "ID:"+(int)id+" "+ + "SEQ:"+command.getInt(LINDA_SEQ_OFFSET)+" "+ + "DATA LENGTH:"+command.getInt(LINDA_DATA_LENGTH_OFFSET)+" "); + if(data!=null) { + System.err.println("DATA:"+data); + data.rewind(); + } + command.rewind(); + } + + static void printData(String comment,ByteBuffer command) { + /*** print data ***/ + char id = (char)command.getShort(LINDA_ID_OFFSET); + System.out.println(comment+" LENGTH:"+command.getInt(LINDA_PACKET_LENGTH_OFFSET)+" "+ + "MODE:"+(char)command.get(LINDA_MODE_OFFSET)+" "+ + "ID:"+(int)id+" "+ + "SEQ:"+command.getInt(LINDA_SEQ_OFFSET)+" "); + command.rewind(); + } + + + static ByteBuffer setCommand(int _mode, int _id, int _seq, ByteBuffer data) { + int _datalen = data==null?0:data.remaining(); + ByteBuffer command = ByteBuffer.allocate(LINDA_HEADER_SIZE); + command.order(ByteOrder.BIG_ENDIAN); + + command.putInt(LINDA_PACKET_LENGTH_OFFSET, + _datalen+LINDA_HEADER_SIZE-INT_SIZE); + command.put(LINDA_MODE_OFFSET,(byte)_mode); + command.putShort(LINDA_ID_OFFSET,(short)_id); + command.putInt(LINDA_SEQ_OFFSET,_seq); + command.putInt(LINDA_DATA_LENGTH_OFFSET,_datalen); + command.rewind(); + return command; + } + + static void setAnserCommand(ByteBuffer command, int seq) { + command.put(LINDA_MODE_OFFSET, (byte)'a'); + command.putInt(LINDA_SEQ_OFFSET, seq); + command.rewind(); + } + + public static ByteBuffer string2ByteBuffer(String log) { + ByteBuffer blog = ByteBuffer.allocate(log.length()*2); // this is incorrect... + for(int i=0;i0 && (data==null||data.remaining()!=command.getInt(LINDA_DATA_LENGTH_OFFSET))) { +// System.err.println("Missing data."); +// } + command.putInt(LINDA_DATA_LENGTH_OFFSET,datalen); + command.putInt(LINDA_PACKET_LENGTH_OFFSET,datalen+LINDA_HEADER_SIZE-INT_SIZE); + command.rewind(); + } + try { + //command Send + while(command.remaining() > 0){ + int count = ch.write(command); + if(count <= 0) throw new IOException(); + } + + command.rewind(); + if (data==null) return; + //data Send + while(data.remaining() > 0){ + int count = ch.write(data); + if(count < 0) throw new IOException(); + } + } catch (IOException e) { + System.out.println("Write Falied on:"+ch); + return; + } + // command or data may be shared among PSX queue + data.rewind(); + } + + public static void send(SelectionKey key, ByteBuffer command, ByteBuffer data) { + SocketChannel ch = (SocketChannel)key.channel(); + send(ch,command,data); + } + + static String getRemoteHostAndPort(SocketChannel ch) { + String socketString = ch.socket().getRemoteSocketAddress().toString(); + String[] split = socketString.split("/"); + int length = split.length; + String hostAndPort = split[length-1]; + split = hostAndPort.split(":"); + String host = split[0]; + String port = split[1]; + int portnum = Integer.parseInt(port); + try { + InetSocketAddress address = new InetSocketAddress(InetAddress.getByName(host), portnum); + host = address.getHostName().toString(); + return (host +":"+port); + } + catch( UnknownHostException e ){ + return hostAndPort; + } + } + + static String getLocalHostAndPort(SocketChannel ch) { + String socketString = ch.socket().getLocalSocketAddress().toString(); + String[] split = socketString.split("/"); + int length = split.length; + String hostAndPort = split[length-1]; + split = hostAndPort.split(":"); + String host = split[0]; + String port = split[1]; + try { + InetAddress localhost = InetAddress.getLocalHost(); + host = localhost.getHostName(); + return (host +":"+port); + } + catch( UnknownHostException e ){ + return (host +":"+port); + } + } + + static void receive(SocketChannel channel, ByteBuffer command, int readsize) + throws IOException { + int count; + if (command.capacity()!=readsize) { + System.err.println("read size mismatch"+readsize+" and "+command.capacity()); + } + while(readsize>0) { + if(false && IOHandler.debug){ + System.out.println("reading packet..."+readsize); + } + count = channel.read(command); + if(count<0) + throw new IOException(); + readsize -= count; + } + command.rewind(); + } + + static ByteBuffer receivePacket(SocketChannel channel, ByteBuffer command) + throws IOException { + /** + * Receive a command and data according to the command. + * + * This read could be very large. Since this Linda server is a single + * thread server, large reading is not welcome. In this case, we should + * start another thread for the large reading. If someone access the + * tuple it should be wait for the reading. This makes rather big changes. + * send routines has the same problem also. I think it is better to limit + * basic tuple size, and introduce cascading tuple type. + * We should try it later. + */ + receive(channel, command,LINDA_HEADER_SIZE); + int datalen = command.getInt(LINDA_DATA_LENGTH_OFFSET); + int packetlen = command.getInt(LINDA_PACKET_LENGTH_OFFSET); + command.rewind(); + if (datalen+LINDA_HEADER_SIZE-INT_SIZE!=packetlen) { + System.err.println("Bad packet received. "+(datalen+LINDA_HEADER_SIZE-INT_SIZE)+"!="+packetlen); + throw new IOException(); + } + ByteBuffer data = ByteBuffer.allocate(datalen); + data.order(ByteOrder.BIG_ENDIAN); +// if (datalen>SINGLE_THREAD_READ_LIMIT) { +// ... make a thread for reading and mark reading flag +// } else + receive(channel, data, datalen); + return data; + } + + +} + +/* end */ diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/PSXLinda.java --- a/src/fdl/PSXLinda.java Sat Feb 16 13:18:02 2008 +0900 +++ b/src/fdl/PSXLinda.java Sun Dec 20 11:44:21 2009 +0900 @@ -1,172 +1,34 @@ - -/* - * @(#)PSXLinda.java 1.1 06/04/01 - * - * Copyright 2006 Shinji KONO - * - - PSX Lidna - Trasport layer of PSX Linda library - - */ - package fdl; import java.io.IOException; -//import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; import java.nio.ByteBuffer; -import java.nio.channels.SelectionKey; -import java.nio.channels.SocketChannel; - - -/** - PSXLinda - * - * @author Shinji Kono - * - * @param mytsid Tuple Space ID - - Initialize connection channel for a tuple space - - one instance for each Tuple space connection - - */ -public class PSXLinda implements PSXQueueInterface { - private FederatedLinda fdl; - private SocketChannel socketChannel; - public String host; - public int port; - public int mytsid; - public PSXLinda next; - static final boolean debug = false; - - public PSXLinda(FederatedLinda _fdl,int _mytsid,String _host,int _port) - throws IOException { - Socket socket; - host = _host; - port = _port; - mytsid = _mytsid; - fdl = _fdl; - - socketChannel = SocketChannel.open(); - socketChannel.configureBlocking(false); - - socket = socketChannel.socket(); - // socket.setReuseAddress(true); - socket.setTcpNoDelay(true); - - // can be blocked (thread required?) - //socketChannel.connect(new InetSocketAddress(InetAddress.getLocalHost(), _port)); - socketChannel.connect(new InetSocketAddress(_host, _port)); - while (! socketChannel.finishConnect()) { - if (debug) { - System.out.println("waiting for connect"); - } -if (false) { - try { - wait(2000); - } catch (InterruptedException e) { - } -} - } - - socketChannel.register(fdl.selector(), SelectionKey.OP_READ); +public interface PSXLinda { - checkConnect("PSXLinda"); - } + public PSXReply in(int id) ; - protected void finalize() { - if (socketChannel != null) { - try { - socketChannel.close(); - } catch (IOException e) { - } - } - } + public void in(int id, PSXCallback callback); - private void checkConnect(String s) { - System.out.print("Connected:"); - System.out.print(s); - System.out.print(": "); - System.out.println(socketChannel.isConnected()); - } + public PSXReply ck(int id) ; - public PSXReply in(int id) { - PSXReply r = fdl.psx_queue(this, id, null, 0, PSX_IN, (PSXCallback)null); - return r; - } - - public void in(int id, PSXCallback callback) { - fdl.psx_queue(this, id, null, 0, PSX_IN, callback); - } - - public PSXReply ck(int id) { - PSXReply r = fdl.psx_queue(this, id, null, 0, PSX_IN, null); - return r; - } + public void ck(int id, PSXCallback callback) ; - public void ck(int id, PSXCallback callback) { - fdl.psx_queue(this, id, null, 0, PSX_IN, callback); - } + public PSXReply out(int id, ByteBuffer data) ; - public PSXReply out(int id, ByteBuffer data,int size) { - PSXReply r = fdl.psx_queue(this, id, data, size, PSX_OUT, null); - return r; - } - - public PSXReply update(int id, ByteBuffer data,int size) { - PSXReply r = fdl.psx_queue(this, id, data, size, PSX_UPDATE, null); - return r; - } + public PSXReply update(int id, ByteBuffer data) ; - public void update(int id, ByteBuffer data,int size,PSXCallback callback) { - fdl.psx_queue(this, id, data, size, PSX_UPDATE, callback); - } - - public PSXReply rd(int id) { - PSXReply r = fdl.psx_queue(this, id, null, 0, PSX_RD, null); - return r; - } + public void update(int id, ByteBuffer data,PSXCallback callback) ; - public void rd(int id, PSXCallback callback) { - fdl.psx_queue(this, id, null, 0, PSX_RD, callback); - } + public PSXReply rd(int id) ; - public PSXLinda add(PSXLinda linda) { - next = linda; - return this; - } + public void rd(int id, PSXCallback callback) ; - public void send(ByteBuffer command,ByteBuffer data) - throws IOException { - if (debug) { - checkConnect("send"); - if (command == null) { - System.out.println("PSXLinda:command is null"); - } - if (data == null) { - System.out.println("PSXLinda:data is null"); - } - } - socketChannel.write(command); - if (data != null) - socketChannel.write(data); - } + public PSXLinda add(PSXLinda linda) ; + + public int sync() throws IOException ; - public int sync() - throws IOException { - return fdl.sync(); - } + public int sync(long mtime) throws IOException ; - public int sync(long mtime) - throws IOException { - return fdl.sync(mtime); - } + public void send(ByteBuffer command, ByteBuffer data); } - - -/* end */ diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/PSXLindaImpl.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/PSXLindaImpl.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,189 @@ + +/* + * @(#)PSXLinda.java 1.1 06/04/01 + * + * Copyright 2006 Shinji KONO + * + + PSX Lidna + Trasport layer of PSX Linda library + + */ + +package fdl; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.SocketChannel; +import java.util.logging.Level; + + +/** + PSXLinda + * + * @author Shinji Kono + * + * @param mytsid Tuple Space ID + + Initialize connection channel for a tuple space + + one instance for each Tuple space connection + + */ + +public class PSXLindaImpl implements PSXLinda,TupleHandler { + private FederatedLinda fdl; + SocketChannel socketChannel; + public String host; + public int port; + public int mytsid; + public PSXLinda next; + static final boolean debug = false; + + public PSXLindaImpl(FederatedLinda _fdl,Selector selector,int _mytsid,String _host,int _port) + throws IOException { + host = _host; + port = _port; + mytsid = _mytsid; + fdl = _fdl; + + socketChannel = SocketChannel.open(); + socketChannel.configureBlocking(false); // Selector needs this + + Socket socket = socketChannel.socket(); + // socket.setReuseAddress(true); Client side don't need this. + socket.setTcpNoDelay(true); + + socketChannel.connect(new InetSocketAddress(_host, _port)); + while (! socketChannel.finishConnect()) { + if (debug) { + fdl.log(Level.INFO,"waiting for connect"); + } + if (false) { + try { + wait(2000); + } catch (InterruptedException e) { + } + } + } + fdl.log(Level.INFO,"Linda client connect to "+socketChannel); + socketChannel.register(selector,SelectionKey.OP_READ,this); + + checkConnect("PSXLinda"); + } + + + public void handle(SelectionKey key) throws ClosedChannelException, + IOException { + SocketChannel sock = (SocketChannel)key.channel(); + if (sock!=socketChannel) { + fdl.log(Level.SEVERE,"wrong socket on PSXLindaImple."); + } + ByteBuffer command = ByteBuffer.allocate(PSX.LINDA_HEADER_SIZE); + command.order(ByteOrder.BIG_ENDIAN); + ByteBuffer data = PSX.receivePacket(sock, command); + + if (debug) { + PSX.printCommand("chkServe:",command, data); + } + + int rseq = command.getInt(PSX.LINDA_SEQ_OFFSET); + int mode = command.get(PSX.LINDA_MODE_OFFSET); + PSXReply r = fdl.getReply(rseq); + if (r==null) { + fdl.log(Level.SEVERE,"Illegal answer sequence."); + return; + } + r.setAnswer(mode,command,data); + + if (r.callback != null ) { + r.callback.callback(data); + } + } + + + protected void finalize() { + if (socketChannel != null) { + try { + socketChannel.close(); + } catch (IOException e) { + } + } + } + + private void checkConnect(String s) { + fdl.log(Level.INFO, "Connected:"+ s +": " + +socketChannel.isConnected()); + } + + public PSXReply in(int id) { + PSXReply r = fdl.psx_queue(this, id, null, PSX.PSX_IN, (PSXCallback)null); + return r; + } + + public void in(int id, PSXCallback callback) { + fdl.psx_queue(this, id, null, PSX.PSX_IN, callback); + } + + public PSXReply ck(int id) { + PSXReply r = fdl.psx_queue(this, id, null, PSX.PSX_IN, null); + return r; + } + + public void ck(int id, PSXCallback callback) { + fdl.psx_queue(this, id, null, PSX.PSX_IN, callback); + } + + public PSXReply out(int id, ByteBuffer data) { + PSXReply r = fdl.psx_queue(this, id, data, PSX.PSX_OUT, null); + return r; + } + + public PSXReply update(int id, ByteBuffer data) { + PSXReply r = fdl.psx_queue(this, id, data, PSX.PSX_UPDATE, null); + return r; + } + + public void update(int id, ByteBuffer data,PSXCallback callback) { + fdl.psx_queue(this, id, data, PSX.PSX_UPDATE, callback); + } + + public PSXReply rd(int id) { + PSXReply r = fdl.psx_queue(this, id, null, PSX.PSX_RD, null); + return r; + } + + public void rd(int id, PSXCallback callback) { + fdl.psx_queue(this, id, null, PSX.PSX_RD, callback); + } + + public PSXLinda add(PSXLinda linda) { + next = linda; + return this; + } + + public int sync() + throws IOException { + return fdl.sync(); + } + + public int sync(long mtime) + throws IOException { + return fdl.sync(mtime); + } + + public void send(ByteBuffer command, ByteBuffer data) { + PSX.send(socketChannel, command, data); + } + + +} + + +/* end */ diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/PSXQueue.java --- a/src/fdl/PSXQueue.java Sat Feb 16 13:18:02 2008 +0900 +++ b/src/fdl/PSXQueue.java Sun Dec 20 11:44:21 2009 +0900 @@ -12,10 +12,7 @@ package fdl; -import java.io.IOException; import java.nio.ByteBuffer; -import java.nio.ByteOrder; -// import java.nio.channels.*; /** PSXQueue @@ -23,51 +20,44 @@ Iterator */ -public class PSXQueue implements PSXQueueInterface { - public int tspace_id; - public int id; - public int mode; - public int size; - public ByteBuffer data; - public ByteBuffer command; - public int seq; - public PSXCallback callback; - public PSXQueue next; - public PSXLinda linda; - - public PSXQueue( PSXLinda _linda,int _id,int _mode,ByteBuffer _data,int _size,PSXCallback _callback) { - linda = _linda; - id = _id; - data = _data; - size = _size; - mode = _mode; - callback = _callback; - setCommand(); - } +public class PSXQueue { + public int tspace_id; + public int id; + public int mode; + public ByteBuffer data; + public int size; + public ByteBuffer command; + public int seq; + public PSXCallback callback; + public PSXQueue next; + public PSXLinda linda; - private void setCommand() { - command = ByteBuffer.allocate(LINDA_HEADER_SIZE); - command.order(ByteOrder.BIG_ENDIAN); - - command.putInt(LINDA_PACKET_LENGTH_OFFSET, - size+LINDA_HEADER_SIZE-INT_SIZE); - command.put(LINDA_MODE_OFFSET,(byte)mode); - command.putShort(LINDA_ID_OFFSET,(short)id); - command.putInt(LINDA_SEQ_OFFSET,seq); - command.putInt(LINDA_DATA_LENGTH_OFFSET,size); - } + public PSXQueue( PSXLinda _linda,int _id,int _mode,ByteBuffer _data,PSXCallback _callback) { + linda = _linda; + id = _id; + data = _data; + if (data!=null) + size = _data.limit()-_data.position(); + else + size = 0; + mode = _mode; + callback = _callback; + setCommand(); + } - public void setSeq(int _seq) { - seq = _seq; - command.putInt(LINDA_SEQ_OFFSET,seq); - } + private void setCommand() { + command = PSX.setCommand(mode,id,seq,data); + } - public void Send() - throws IOException { - if (command!=null) command.rewind(); - if (data!=null) data.rewind(); - linda.send(command,data); - } + public void setSeq(int _seq) { + seq = _seq; + command.putInt(PSX.LINDA_SEQ_OFFSET,seq); + command.rewind(); + } + + public void send() { + linda.send(command, data); + } } /* end */ diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/PSXQueueInterface.java --- a/src/fdl/PSXQueueInterface.java Sat Feb 16 13:18:02 2008 +0900 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,48 +0,0 @@ - -/* - * @(#)PSXQueueInterface.java 1.1 06/04/01 - * - * Copyright 2006 Shinji KONO - * - - PSX Lidna - Trasport layer of PSX Linda library - - */ - -package fdl; - - -/** - PSXQueueInterface - - Iterator - */ - -public interface PSXQueueInterface { - static final int PSX_IN = 'i'; - static final int PSX_OUT = 'o'; - static final int PSX_UPDATE = 'u'; - static final int PSX_RD = 'r'; - static final int PSX_CHECK = 'c'; - static final int PSX_REPLY = '?'; - static final int PSX_WAIT_RD = 'w'; - static final int PSX_ANSWER = 'a'; - static final int PSX_HTTP_ANSWER = 'P'; // Put - static final int PSX_HTTP_REQUEST = 'G'; // Get - static final int PSX_COM_DEBUG = 'D'; //Communication DEBUG - - static final int LINDA_PACKET_LENGTH_OFFSET =0; - static final int LINDA_MODE_OFFSET =0+4; - static final int LINDA_ID_OFFSET =1+4; - static final int LINDA_SEQ_OFFSET =3+4; - static final int LINDA_DATA_LENGTH_OFFSET =7+4; - static final int LINDA_HEADER_SIZE =12+4; - static final int INT_SIZE =4; - static final int SHORT_SIZE =2; - - static final int PRIVILEGED_ID_START = 32768; - static final int PRIVILEGED_ID_END = 36864; -} - -/* end */ diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/PSXReply.java --- a/src/fdl/PSXReply.java Sat Feb 16 13:18:02 2008 +0900 +++ b/src/fdl/PSXReply.java Sun Dec 20 11:44:21 2009 +0900 @@ -16,59 +16,52 @@ package fdl; import java.nio.ByteBuffer; -public class PSXReply implements PSXQueueInterface { - public ByteBuffer command; - public ByteBuffer data; - public int seq; - public PSXReply next; - public int mode; - public PSXCallback callback; - static final boolean debug = false; +public class PSXReply { + public ByteBuffer command; + public ByteBuffer data; + public int seq; + public PSXReply next; + public int mode; + public PSXCallback callback; - public PSXReply(int _mode,PSXCallback _callback) { - mode = _mode; - callback = _callback; - } - - public PSXReply() { - } + public PSXReply(int _mode,PSXCallback _callback) { + mode = _mode; + callback = _callback; + } - public void setAnswer(int _mode, ByteBuffer _command,ByteBuffer _data) { - mode = _mode; - data = _data; - command = _command; - if (debug) { -System.out.print("setAnswer mode:"); -System.out.println(mode); -System.out.print("setAnswer bool:"); -System.out.println(mode==PSX_ANSWER); + public PSXReply() { + } + + public void setAnswer(int _mode, ByteBuffer _command,ByteBuffer _data) { + mode = _mode; + data = _data; + command = _command; } - } + + public int getMode() { + return command.get(PSX.LINDA_MODE_OFFSET); + } - public int getMode() { - return command.get(LINDA_MODE_OFFSET); - } + public int getId() { + return command.getShort(PSX.LINDA_ID_OFFSET); + } - public int getId() { - return command.getShort(LINDA_ID_OFFSET); - } + public int getSeq() { + return command.getInt(PSX.LINDA_SEQ_OFFSET); + } - public int getSeq() { - return command.getInt(LINDA_SEQ_OFFSET); - } - - public int getLength() { - return command.getInt(LINDA_DATA_LENGTH_OFFSET); - } + public int getLength() { + return command.getInt(PSX.LINDA_DATA_LENGTH_OFFSET); + } - public ByteBuffer getData() { - data.rewind(); - return data; - } + public ByteBuffer getData() { + data.rewind(); + return data; + } - public boolean ready() { - return mode==PSX_ANSWER; - } + public boolean ready() { + return mode==PSX.PSX_ANSWER; + } } diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/TestEtc.java --- a/src/fdl/TestEtc.java Sat Feb 16 13:18:02 2008 +0900 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,43 +0,0 @@ - -package fdl; - -import java.io.IOException; -//import java.nio.ByteBuffer; - -public class TestEtc implements PSXQueueInterface { - static final int MAX_REQ = 1; - static final int FAIL = (-1); - static final int MAX_UAER = 4; - static final int MAX_TUPLE = 65536; - static final int MAX_BUFFSIZE = 2048; - static final int DEF_PORT = 10000; - static final String PATHNAME = "/tmp/ldserv"; - - - static final int LINDA_MODE_OFFSET = 0; - static final int LINDA_ID_OFFSET = 1; - static final int LINDA_SEQ_OFFSET = 3; - static final int LINDA_DATA_LENGTH_OFFSET = 7; - static final int LINDA_HEADER_SIZE = 12; - - static final boolean debug = true; - public PSXQueue tuple_space; - public PSXQueue tp; - - public static void main(String[] args) throws IOException { - String socketString = "java.nio.channels.SocketChannel[connected local=/133.13.57.210:10001 remote=/133.13.57.210:50634]"; - String[] split = socketString.split("/"); - String local[] = split[1].split(" "); - String remote[] = split[2].split("]"); - - @SuppressWarnings("unused") - final String localAddress = local[0]; - @SuppressWarnings("unused") - final String remoteAddress = remote[0]; - - System.out.println(local[0]); - System.out.println(remote[0]); -// System.out.println("tmpTuple "+tmpTuple.toString()); -// System.out.println("testTS "+testTS[MAX_TUPLE-1].toString()); - } -} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/TestPSXLinda.java --- a/src/fdl/TestPSXLinda.java Sat Feb 16 13:18:02 2008 +0900 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,81 +0,0 @@ - -/* - * @(#)TestPSXLinda.java 1.1 06/04/01 - * - * Copyright 2006 Shinji KONO - * - - Test PSX Lidna - - */ - -package fdl; - -import java.io.IOException; -import java.nio.ByteBuffer; - - -/** - * PSXLinda stream - * - * @author Shinji Kono - * - * @param host The host to connect to - * @param port The port to connect to at the host - - */ - - -class TestPSXLinda { - static int id; - public static void main (String args[]) { - - FederatedLinda fdl; - PSXLinda psx; - String host = "localhost"; - int port = 10000; - PSXReply r; - - - // try { - // port = Integer.parseInt(args[1]); - // } catch (NumberFormatException nfex) { } - try { - fdl = FederatedLinda.init(); - psx = fdl.open(host,port); - r = psx.in(65535); - //for(int i=0;i<100;i++) { - //if (1==0) { - //} - fdl.sync(1); - //} - System.out.println("Connected."); - - ByteBuffer data = ByteBuffer.allocate(10); - data.putInt(10); - - psx.out(1,data,4); - - while(!r.ready()) { - psx.sync(1000); - // System.out.println("Waiting...."); - } - } catch (IOException nfex) { - nfex.printStackTrace(); - System.out.println("Faild."); - return; - } - - print_id(r); - - - } - - public static void print_id (PSXReply ans) { - ByteBuffer r = ans.getData(); - id = r.getShort(); - System.out.print("ID = "); - System.out.println(id); - } -} - diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/Tuple.java --- a/src/fdl/Tuple.java Sat Feb 16 13:18:02 2008 +0900 +++ b/src/fdl/Tuple.java Sun Dec 20 11:44:21 2009 +0900 @@ -2,69 +2,41 @@ package fdl; import java.nio.ByteBuffer; -import java.nio.ByteOrder; import java.nio.channels.SocketChannel; - -public class Tuple implements PSXQueueInterface { +public class Tuple { public int mode; public int id; public int seq; - public int datalen; public ByteBuffer command; public ByteBuffer data; + // a Tuple muse remember the answer destination + public SocketChannel ch; public Tuple next; - public SocketChannel ch; static final boolean debug = false; - public Tuple(SocketChannel _ch) { - ch = _ch; - } - public Tuple() { } - public void setCommand(int _mode, int _seq) { - command = ByteBuffer.allocate(LINDA_HEADER_SIZE); - command.order(ByteOrder.BIG_ENDIAN); - - command.putInt(LINDA_PACKET_LENGTH_OFFSET, - this.datalen+LINDA_HEADER_SIZE-INT_SIZE); - command.put(LINDA_MODE_OFFSET,(byte)_mode); - command.putShort(LINDA_ID_OFFSET,(short)this.id); - command.putInt(LINDA_SEQ_OFFSET,_seq); - command.putInt(LINDA_DATA_LENGTH_OFFSET,this.datalen); - command.rewind(); + public Tuple(SocketChannel ch) { + this.ch = ch; } - - public void setCommand(int _mode, int _id, int _seq, int _datalen) { - command = ByteBuffer.allocate(LINDA_HEADER_SIZE); - command.order(ByteOrder.BIG_ENDIAN); - - command.putInt(LINDA_PACKET_LENGTH_OFFSET, - _datalen+LINDA_HEADER_SIZE-INT_SIZE); - command.put(LINDA_MODE_OFFSET,(byte)_mode); - command.putShort(LINDA_ID_OFFSET,(short)_id); - command.putInt(LINDA_SEQ_OFFSET,_seq); - command.putInt(LINDA_DATA_LENGTH_OFFSET,_datalen); - command.rewind(); + public void setCommand(int _mode, int _seq) { + setCommand( _mode, id, _seq,data); } - public void setTuple(int _mode,int _id, int _seq, int _datalen, ByteBuffer _data) { - mode = _mode; - id = _id; - seq = _seq; - datalen = _datalen; - data = _data; - - if (debug) { - System.out.print("setTuple mode:"); - System.out.println(mode); - } - //setCommand(); + public void setCommand(int _mode, int _id, int _seq, ByteBuffer data) { + command = PSX.setCommand(_mode, _id, _seq, data); } + + public void setTuple(int _mode,int _id, int _seq, ByteBuffer _data) { + mode = _mode; + id = _id; + seq = _seq; + data = _data; + } public void setSeq(int _seq) { seq = _seq; @@ -73,13 +45,8 @@ public void setMode(int _mode) { mode = _mode; } - - public void setDataLength(int _datalength) { - datalen = _datalength; - } public void setData(ByteBuffer _data) { - _data.rewind(); data = _data; } @@ -87,34 +54,19 @@ return mode; } - /*public int getId() { - return command.getShort(LINDA_ID_OFFSET); - }*/ - public int getSeq() { return seq; } public int getdataLength() { - return datalen; + return data==null?0:data.remaining(); } + public ByteBuffer getData() { - data.rewind(); return data; } public ByteBuffer getCommand() { return this.command; } - /*public ByteBuffer getCommand() { - command = ByteBuffer.allocate(LINDA_HEADER_SIZE); - command.order(ByteOrder.BIG_ENDIAN); - command.putInt(LINDA_PACKET_LENGTH_OFFSET, LINDA_HEADER_SIZE+datalen-INT_SIZE); - command.put(LINDA_MODE_OFFSET, (byte)mode); - command.putShort(LINDA_ID_OFFSET,(short)id); - command.putInt(LINDA_SEQ_OFFSET, seq); - command.putInt(LINDA_DATA_LENGTH_OFFSET, datalen); - command.rewind(); - return command; - }*/ } diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/TupleHandler.java --- a/src/fdl/TupleHandler.java Sat Feb 16 13:18:02 2008 +0900 +++ b/src/fdl/TupleHandler.java Sun Dec 20 11:44:21 2009 +0900 @@ -5,9 +5,7 @@ import java.nio.channels.SelectionKey; public interface TupleHandler { - static final int MAX_TUPLE = 65536; - static final int MAX_USER = 4; - static final int BUFSIZE = 65535; + static final int MAX_USER = 99; public int user = 0; public void handle(SelectionKey key) throws ClosedChannelException, IOException; diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/TupleSpace.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/TupleSpace.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,295 @@ +package fdl; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.SocketChannel; +import java.util.logging.Level; + +public class TupleSpace { + static final boolean debug = true; + public static int user = 0; + public Tuple[] tuple_space; + public IOHandlerHook hook = new NullIOHandlerHook(); + private FDLindaServ fds; + public static final int MAX_TUPLE_ID = 65536; + + public TupleSpace(FDLindaServ fds) { + // 読みこんだデータを格納するためのリストの初期化 + tuple_space = new Tuple[MAX_TUPLE_ID]; + this.fds = fds; + } + + + public void newUser() { + Tuple tuple; + //初期生成 + if((tuple = tuple_space[MAX_TUPLE_ID-1]) == null) { + tuple = tuple_space[MAX_TUPLE_ID-1] = new Tuple(); + tuple.next = null; + } else { + while(tuple.next != null) tuple = tuple.next; + tuple.next = new Tuple(); + tuple = tuple.next; + tuple.next = null; + } + + user++; + + ByteBuffer data = ByteBuffer.allocate(10); + ByteBuffer r = ByteBuffer.allocate(10); + int value = user; + while(value>0) { + r.put((byte) (value%10 + '0')); + value /= 10; + } + for(int i=r.position()-1;i>=0;i--) { + data.put(r.get(i)); + } + data.flip(); + + int id = TupleSpace.MAX_TUPLE_ID-1; + int seq = 0; + tuple.setTuple('o', id, seq, data); + fds.log(Level.INFO,"Server: assign id "+user); + } + + protected void Out(SelectionKey key,ByteBuffer command, ByteBuffer data) { + Tuple tuple; + int id; + int datasize; + char idc = (char)command.getShort(PSX.LINDA_ID_OFFSET); + command.rewind(); + id = (int)idc; + + datasize = command.getInt(PSX.LINDA_DATA_LENGTH_OFFSET); + command.rewind(); + + if (debug) fds.log(Level.INFO,"*** out command : id = "+id +" ***"); + int seq = command.getInt(PSX.LINDA_SEQ_OFFSET); + command.rewind(); + hook.outHook(key,id,seq,'o',data); + + while((tuple_space[id] != null) && + ((tuple_space[id].mode == PSX.PSX_WAIT_RD)||(tuple_space[id].mode == PSX.PSX_RD))) { + PSX.setAnserCommand(command, tuple_space[id].getSeq()); + PSX.send(tuple_space[id].ch, command, data); + + removeTuple(id); + tuple = null; + } + if(tuple_space[id] != null && tuple_space[id].mode == PSX.PSX_IN) { + PSX.setAnserCommand(command, tuple_space[id].getSeq()); + + if(debug){ + if (debug) fds.log(Level.INFO,"send size "+datasize+" : mode = "+(char)'a'); + } + PSX.send(tuple_space[id].ch, command, data); + removeTuple(id); + tuple = null; + // Incoming Out tuple is consumed here, and wating IN tuple is also removed. + } else if ((tuple_space[id] == null)|| (tuple_space[id].getMode() == PSX.PSX_OUT)) { + if((tuple = tuple_space[id]) == null) { + tuple = tuple_space[id] = new Tuple(); + tuple.next = null; + } + else { + while(tuple.next != null) tuple = tuple.next; + tuple.next = new Tuple(); + tuple = tuple.next; + tuple.next = null; + } + + tuple.setMode('o'); + tuple.setSeq(seq); + tuple.setData(data); + if(debug){ + fds.log(Level.INFO, "data inserted len = "+tuple.getdataLength()+" : id = "+id); + } + } else { + fds.log(Level.SEVERE, "Incorrect mode :"+(char)tuple_space[id].getMode()); + } + } + + private void removeTuple(int id) { + Tuple tuple; + //後処理 + tuple = tuple_space[id]; + tuple_space[id] = tuple.next; + } + + protected void Wait_Rd(SelectionKey key, ByteBuffer command, int mode) { + Tuple tuple; + int id; + + char idc = (char)command.getShort(PSX.LINDA_ID_OFFSET); + command.rewind(); + id = (int)idc; + + if (debug) + fds.log(Level.INFO, "*** "+(char)mode+" command : id = "+ id +" ***\n"); + + tuple = new Tuple(); + tuple.setMode(mode); + int seq = command.getInt(PSX.LINDA_SEQ_OFFSET); + command.rewind(); + tuple.setSeq(seq); + + hook.waitReadHook(key,id,seq,(char)mode); + + tuple.ch = (SocketChannel) key.channel(); + ByteBuffer buff = ByteBuffer.allocate(0); + tuple.setData(buff); + tuple.next = tuple_space[id]; + tuple_space[id] = tuple; + if(debug){ + fds.log(Level.INFO, "data inserted insert seq = "+seq +", id = "+id); + } + } + + protected void In_Rd(SelectionKey key, ByteBuffer command, int mode) + throws IOException { + Tuple tuple = read_in_1(key, command, mode); + + if (tuple!=null) { + //send + ByteBuffer sendcommand = tuple.getCommand(); + ByteBuffer senddata = tuple.getData(); + PSX.send(key,sendcommand, senddata); + } + } + + private Tuple read_in_1(SelectionKey key, ByteBuffer command, int mode) { + Tuple tuple; + int id; + //id = command.getInt(PSX.LINDA_ID_OFFSET); + //int mode = command.getInt(PSX.LINDA_MODE_OFFSET); + Tuple temp = null; + + char idc = (char)command.getShort(PSX.LINDA_ID_OFFSET); + id = (int)idc; + int seq = command.getInt(PSX.LINDA_SEQ_OFFSET); + command.rewind(); + + if (debug) fds.log(Level.INFO, "*** "+(char)mode+" command : id = "+ id +" ***\n"); + hook.inHook(key,id,seq,(char)mode); + + tuple = tuple_space[id]; + + //wを無視 + while(tuple != null && tuple.next != null && (tuple.mode == 'w')){ + temp = tuple; + tuple = tuple.next; + } + + if (tuple != null && (tuple.mode == 'o')){ + tuple.seq = seq; + tuple = tupleIsAvailable(command, mode, tuple, id, temp); + } else { + tuple = setupWait(key, command, mode, tuple, seq, id); + } + return tuple; + } + + public ByteBuffer IN(int id,int mode, ByteBuffer command) { + /** + * IN for MetaLinda (no wait); + */ + Tuple tuple,temp=null; + tuple = tuple_space[id]; + + //wを無視 + while(tuple != null && tuple.next != null && (tuple.mode == 'w')){ + temp = tuple; + tuple = tuple.next; + } + + if (tuple != null && (tuple.mode == 'o')){ + ByteBuffer data = tuple.data; + tuple.seq = 0; + tupleIsAvailable(command, mode, tuple, id, temp); + return data; + } + return null; + } + + private Tuple tupleIsAvailable(ByteBuffer command, int mode, Tuple tuple, + int id, Tuple temp) { + tuple.setCommand('a', tuple.seq); + + if(debug){ + int sendsize = tuple.getdataLength()+PSX.LINDA_HEADER_SIZE; + fds.log(Level.INFO, "send size "+sendsize+" : mode = "+(char)tuple.getMode()); + } + //INの場合はremoveする + if(mode == PSX.PSX_IN) { + if(temp != null){ + temp.next = tuple.next; + } + else { + tuple_space[id] = tuple.next; + } + } + return tuple; + } + + private Tuple setupWait(SelectionKey key, ByteBuffer command, int mode, + Tuple tuple, int seq, int id) { + if(tuple == null) { + tuple = tuple_space[id] = new Tuple((SocketChannel)key.channel()); + tuple.next = null; + }else { + while(tuple.next !=null) tuple =tuple.next; + tuple.next= new Tuple((SocketChannel)key.channel()); + tuple = tuple.next; + tuple.next = null; + } + + tuple.setMode(mode); + tuple.setSeq(seq); + tuple.ch = (SocketChannel) key.channel(); + ByteBuffer buff = ByteBuffer.allocate(0); + tuple.setData(buff); + tuple = null; + + if(debug){ + fds.log(Level.INFO, "wait inserted seq = "+seq +", id = "+id); + } + return tuple; + } + + protected void Check(SelectionKey key, ByteBuffer command) throws IOException { + ByteBuffer data = check1(key,command); + PSX.send(key, command, data); + } + + public ByteBuffer check1(SelectionKey key,ByteBuffer command) { + ByteBuffer data; + Tuple tmpTuple; + int id; + char idc = (char)command.getShort(PSX.LINDA_ID_OFFSET); + command.rewind(); + id = (int)idc; + int seq = command.getInt(PSX.LINDA_SEQ_OFFSET); + command.rewind(); + hook.checkHook(key,id,seq,'c'); + + tmpTuple = tuple_space[id]; + while(tmpTuple != null && tmpTuple.next != null && (tmpTuple.mode == 'w')){ + tmpTuple = tmpTuple.next; + } + if (tmpTuple != null && (tmpTuple.mode == 'o')) { + command.putInt(PSX.LINDA_DATA_LENGTH_OFFSET, tmpTuple.getdataLength()); + command.rewind(); + data = tmpTuple.getData(); + }else { + //means no out tuple + command.putInt(PSX.LINDA_DATA_LENGTH_OFFSET, 0); + command.rewind(); + data = ByteBuffer.allocate(0); + } + return data; + } + + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/URLKicker.java --- a/src/fdl/URLKicker.java Sat Feb 16 13:18:02 2008 +0900 +++ b/src/fdl/URLKicker.java Sun Dec 20 11:44:21 2009 +0900 @@ -11,9 +11,10 @@ package fdl; -import java.net.*; -import java.io.*; -// mport java.nio.*; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; /** diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/package-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/package-info.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,11 @@ +/** + * Asynchronous Federated Linda Servers and Clients Library. + *

+ * Linda server provides Tuple space, which is accessed by Linda clients. + * Multiple Linda servers are connected by Protocol Engines. A Linda client + * handles multiple Linda server at once. All communications are handled + * asynchronous way, that is, it does not wait for the completion. + * + * @since 1.0 + */ +package fdl; diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/ComDebug_Client.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/ComDebug_Client.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,103 @@ +package fdl.test; + + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.LinkedList; + +import fdl.FederatedLinda; +import fdl.PSX; +import fdl.PSXCallback; +import fdl.PSXLinda; + +/* + * それぞれのLinda Serverのmeta protocolに接続して、順々にモニタデータを + * 受け取って表示する。 + */ +public class ComDebug_Client { + + static int id; + static final boolean debug = false; + PSXCallback debugCallback ; + + FederatedLinda fdl; + PSXLinda psx; + LinkedList hosts = new LinkedList(); + LinkedList ports = new LinkedList(); + LinkedList psxs = new LinkedList(); + + public static void main(String[] args) { + ComDebug_Client com = new ComDebug_Client(); + com.run(args); + } + + public void run(String[] args) { + int connect_num = 1; + final String usages = "usage: ComDebug_Client [-h host -p port]*"; + //引数判定 + try { + if (args.length < 2) { + System.err.println(usages); + } + + for (int i=0; i"+reply); + } + }; + psx.in(65535, checkid); + + System.out.println("COM_DEBUG Connected.["+host+":"+port+"]"); + psx.out(PSX.META_MONITOR, null); + debugCallback = + new PSXCallback() { + public void callback(ByteBuffer reply) { + System.out.println("COM_DEBUG: "+PSX.getdataString(reply)); + psx.out(PSX.META_MONITOR, null); + psx.in(PSX.META_MONITOR_DATA,debugCallback); + } + }; + psx.out(PSX.META_MONITOR, null); + psx.in(PSX.META_MONITOR_DATA,debugCallback); + + connect_num++; + } + while(true) { + fdl.sync(1000); + } + } catch (IOException nfex) { + nfex.printStackTrace(); + System.out.println("Faild."); + return; + } + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/TestEtc.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/TestEtc.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,44 @@ + +package fdl.test; + +import java.io.IOException; + +import fdl.PSXQueue; + +public class TestEtc { + static final int MAX_REQ = 1; + static final int FAIL = (-1); + static final int MAX_UAER = 4; + static final int MAX_TUPLE = 65536; + static final int MAX_BUFFSIZE = 2048; + static final int DEF_PORT = 10000; + static final String PATHNAME = "/tmp/ldserv"; + + + static final int LINDA_MODE_OFFSET = 0; + static final int LINDA_ID_OFFSET = 1; + static final int LINDA_SEQ_OFFSET = 3; + static final int LINDA_DATA_LENGTH_OFFSET = 7; + static final int LINDA_HEADER_SIZE = 12; + + static final boolean debug = true; + public PSXQueue tuple_space; + public PSXQueue tp; + + public static void main(String[] args) throws IOException { + String socketString = "java.nio.channels.SocketChannel[connected local=/133.13.57.210:10001 remote=/133.13.57.210:50634]"; + String[] split = socketString.split("/"); + String local[] = split[1].split(" "); + String remote[] = split[2].split("]"); + + @SuppressWarnings("unused") + final String localAddress = local[0]; + @SuppressWarnings("unused") + final String remoteAddress = remote[0]; + + System.out.println(local[0]); + System.out.println(remote[0]); +// System.out.println("tmpTuple "+tmpTuple.toString()); +// System.out.println("testTS "+testTS[MAX_TUPLE-1].toString()); + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/TestLindaServer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/TestLindaServer.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,46 @@ +package fdl.test; + +import fdl.FDLindaServ; +import fdl.FederatedLinda; + +public class TestLindaServer { + public FederatedLinda fdl; + public FDLindaServ fds; + public static final int PORT = 10000; + + class Server implements Runnable { + public void run() { + String[] args = {"-p",Integer.toString(PORT)}; + FDLindaServ.main(args); + } + } + + class Client implements Runnable { + public void run() { + String[] args = {}; + sleep(2000); + TestPSXLinda.main(args); + } + public synchronized void sleep(int time) { + try { + wait(time); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + public static void main(String[] arg) { + TestLindaServer me = new TestLindaServer(); + me.test1(); + } + + public void test1() { + Server s = new Server(); + Client c = new Client(); + new Thread(s).start(); + new Thread(c).start(); + } + + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/TestMetaLinda.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/TestMetaLinda.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,88 @@ +/* + * @(#)TestMetaLinda.java 1.1 06/04/01 + * + * Copyright 2006 Shinji KONO + * + + Test PSX Lidna + + */ + +package fdl.test; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSX; +import fdl.PSXLinda; +import fdl.PSXReply; + + +/** + * PSXLinda stream + * + * @author Shinji Kono + * + * @param localhost The host to connect to + * @param Port The port to connect to at the host + + */ + + +public class TestMetaLinda { + static int id; + public static void main (String args[]) { + + FederatedLinda fdl; + PSXLinda psx; + String host; + int port = 10000; + PSXReply r; + InetSocketAddress localAddress; + + + try { + localAddress = new InetSocketAddress(InetAddress.getLocalHost(), port); + host = localAddress.getHostName(); + } catch (UnknownHostException e) { + host = "localhost"; + } + + try { + fdl = FederatedLinda.init(); + psx = fdl.open(host,port); + System.out.println("Connected."); + + r = psx.in(1); + + for(int i=0;i<10;i++) { + ByteBuffer data = ByteBuffer.allocate(10); + data.putInt(i); + data.flip(); + psx.out(1,data); + } + for(int i=0;i<50;i++) { + if (r.ready()) { + System.err.println("Get:"+r.data.getInt()); + r = psx.in(1); + } + // System.out.println("syncing..."+i); + psx.sync(100); + } + + System.out.println("Try to stop the server"); + psx.out(PSX.META_STOP, null); + psx.sync(100); + + } catch (IOException e) { + System.err.println("Communication failure."); + } + } + + +} + diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/TestMonitor.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/TestMonitor.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,82 @@ +package fdl.test; + +import java.net.InetAddress; +import java.net.UnknownHostException; + +import fdl.FDLindaServ; +import fdl.FederatedLinda; + +public class TestMonitor { + + public FederatedLinda fdl; + public FDLindaServ fds; + public String localhost; + public static final int PORT = 10000; + + class Server implements Runnable { + public void run() { + String[] args = {"-p",Integer.toString(PORT)}; + System.out.println("Linda server start."); + FDLindaServ.main(args); + } + } + + class Client implements Runnable { + public void run() { + String[] args = {}; + sleep(4000); + System.err.println("Client start."); + TestMetaLinda.main(args); + } + public synchronized void sleep(int time) { + try { + wait(time); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + class Monitor implements Runnable { + public void run() { + String[] args = {"-h",localhost,"-p",Integer.toString(PORT)}; + sleep(2000); + System.err.println("Monitor start."); + ComDebug_Client.main(args); + } + public synchronized void sleep(int time) { + try { + wait(time); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + public static void main(String[] arg) { + TestMonitor me = new TestMonitor(); + me.test1(); + } + + public void test1() { + try { + localhost = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + return; + } + System.err.println("Monitor Test start."); + Server s = new Server(); + Client c = new Client(); + Monitor m = new Monitor(); + Thread ts = new Thread(s); ts.start(); + Thread tm = new Thread(m); tm.start(); + Thread tc = new Thread(c); tc.start(); + try { + ts.join(); tm.join(); + tc.join(); + } catch (InterruptedException e) { + } + } + + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/TestPSXLinda.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/TestPSXLinda.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,94 @@ + +/* + * @(#)TestPSXLinda.java 1.1 06/04/01 + * + * Copyright 2006 Shinji KONO + * + + Test PSX Lidna + + */ + +package fdl.test; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSX; +import fdl.PSXLinda; +import fdl.PSXReply; + + +/** + * PSXLinda stream + * + * @author Shinji Kono + * + * @param localhost The host to connect to + * @param Port The port to connect to at the host + + */ + + +class TestPSXLinda { + static int id; + public static void main (String args[]) { + + FederatedLinda fdl; + PSXLinda psx; + String host; + int port = 10000; + PSXReply r; + InetSocketAddress localAddress; + + + try { + localAddress = new InetSocketAddress(InetAddress.getLocalHost(), port); + host = localAddress.getHostName(); + } catch (UnknownHostException e) { + host = "localhost"; + } + + try { + fdl = FederatedLinda.init(); + psx = fdl.open(host,port); + r = psx.in(65535); + fdl.sync(1); + System.out.println("Connected."); + + ByteBuffer data = ByteBuffer.allocate(10); + data.putInt(10); + data.flip(); + + psx.out(1,data); + + int cnt=0; + while(!r.ready()) { + // psx.sync(1000); + psx.sync(); + System.out.println("Waiting...."+(cnt++)); + } + + print_id(r); + + data.clear(); + psx.out(PSX.META_STOP, data); + psx.sync(); + + } catch (IOException e) { + System.err.println("Communication failure."); + } + } + + public static void print_id (PSXReply ans) { + ByteBuffer r = ans.getData(); + id = r.getShort(); + System.out.print("ID = "); + System.out.println(id); + } +} + diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/FDLServWithSend.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/FDLServWithSend.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,23 @@ +package fdl.test.metaTransfer; + +import java.io.IOException; + +import fdl.FDLindaServ; +import fdl.MetaLinda; + + +public class FDLServWithSend extends FDLindaServ { + int port1; + public FDLServWithSend(int port,int port1) throws IOException { + super(port); + this.port1 = port1; + } + + @Override public void mainLoop() { + System.out.println("change mainloop"); + MetaLinda ml = new MetaLinda(tupleSpace, this); + MetaProtocolEngine mpe = new MetaProtocolEngine(ml,"MetaEngine", port1); + mpe.mainLoop(); + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/MetaProtocolEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/MetaProtocolEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,95 @@ +package fdl.test.metaTransfer; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.MetaEngine; +import fdl.MetaLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + +public class MetaProtocolEngine implements MetaEngine { + private int id = 10; + private boolean running = true; + + private PSXLinda psx; + private String name; + MetaLinda fdl1; + String host = "127.0.0.1"; + int port1; + private PSXLinda psx1; + private ByteBuffer data2 = ByteBuffer.allocate(10); + private int count = 1; + + + public MetaProtocolEngine(MetaLinda ml, String string, int port1) { + this.name = string; + this.port1 = port1; + this.fdl1 = ml; + } + + public void mainLoop(){ + boolean connect = true; + System.out.println("MetaEngine Start"); + while(connect){ + try { + initConnect(); + transfer(); + connect = false; + } catch (IOException e) { + try { + Thread.sleep(40); + } catch (InterruptedException e1) { + } + } + } + } + + private void initConnect(){ + System.out.println(name); + boolean connectpsx = true; + while(connectpsx){ + try { + psx = fdl1.open(host,port1); + connectpsx = false; + } catch (IOException e) { + try { + Thread.sleep(40); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + } + } + System.out.println("Connect "+port1); + psx1 = fdl1; + } + + private void transfer() throws IOException { + PSXReply in = psx.in(id); + System.out.println("PSXReply "+port1); + while (running) { + if(in.ready()){ + data2 = in.getData(); + int i = data2.getInt(); + data2.rewind(); + //outしたbytebufferの変更をこれ以降やっちゃいけない + psx1.out(id,data2); + + System.out.println("IntData0 "+port1 +i); + fdl1.sync(); + if (count++>3) { + running = false; + break; + } + System.out.println("IntData1 "+port1 +i); + } + fdl1.sync(); + } + assertEquals(4,count); + } + + +} + diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/MetaProtocolEngine_not.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/MetaProtocolEngine_not.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,73 @@ +package fdl.test.metaTransfer; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.MetaEngine; +import fdl.MetaLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + + +public class MetaProtocolEngine_not implements MetaEngine { + private FederatedLinda fdlmeta; + private ByteBuffer data = ByteBuffer.allocate(1024); + private int id = 10; + private boolean running = true; + + //ここからsend用宣言 + private PSXLinda sendpsx,getpsx; + private String host = "127.0.0.1"; + private int port; + + public MetaProtocolEngine_not(MetaLinda fdlmeta, int port) { + this.port = port; + } + + public void metaOpen(int sendport){ + try{ + sendpsx = fdlmeta.open(host, sendport); + }catch (IOException e) { + e.printStackTrace(); + } + } + + //meta部分のデータ取得 + public void metaTrans() { + try { + getpsx = fdlmeta.open(host, 10001); + } catch (IOException e) { + e.printStackTrace(); + } + PSXReply in = getpsx.in(id); + while (running) { + System.out.println(in); + System.out.println(in.ready()); + if(in.ready()) { + data = in.getData(); + sendpsx.out(id, data); + running = false; + break; + } + } + } + + + public void mainLoop() { + System.out.println("MetaProtocolEngine Start"); + fdlmeta = FederatedLinda.init(); + if( port == 10002 ) { + metaOpen(10003); + metaTrans(); + try { + fdlmeta.sync(); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("MetaProtocolEngine Connect"); + } + + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/Ring/FDLServWithSend.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/Ring/FDLServWithSend.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,22 @@ +package fdl.test.metaTransfer.Ring; + +import java.io.IOException; + +import fdl.FDLindaServ; +import fdl.MetaLinda; + +public class FDLServWithSend extends FDLindaServ { + int port1; + public FDLServWithSend(int port,int port1) throws IOException { + super(port); + this.port1 = port1; + } + + @Override public void mainLoop() { + System.out.println("change mainloop"); + MetaLinda ml = new MetaLinda(tupleSpace, this); + MetaProtocolEngine mpe = new MetaProtocolEngine(ml,"MetaEngine", port1, port1); + mpe.mainLoop(); + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/Ring/MetaProtocolEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/Ring/MetaProtocolEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,100 @@ +package fdl.test.metaTransfer.Ring; + +//import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.MetaEngine; +import fdl.MetaLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + +public class MetaProtocolEngine implements MetaEngine { + int id = 10; + private boolean running = true; + + private PSXLinda psx; + private String name; + MetaLinda fdl1; + String host = "127.0.0.1"; + int port1; + private PSXLinda psx1; + private ByteBuffer data = ByteBuffer.allocate(10); +// private int count = 1; + int port; + + + public MetaProtocolEngine(MetaLinda ml, String string, int port1, int port) { + this.name = string; + this.port1 = port1; + this.fdl1 = ml; + this.port = port; + } + + public void mainLoop(){ + boolean connect = true; + System.out.println("MetaEngine Start"); + while(connect){ + try { + initConnect(); + transfer(psx, psx1); + connect = false; + } catch (IOException e) { + try { + Thread.sleep(40); + } catch (InterruptedException e1) { + } + } + } + } + + private void initConnect() throws IOException{ + System.out.println(name); + //自分 + psx = fdl1; + if (port == 10001){ + sendData(); + } + //相手 + psx1 = fdl1.open(host,port1); + System.out.println("Connect "+port1); + } + + private void sendData() throws IOException{ + boolean connectSend = true; + ByteBuffer send = ByteBuffer.allocate(1024); + send.putInt(12); + send.flip(); + while(connectSend){ + psx.out(id, send); + fdl1.sync(1); + System.out.println("Send Data 10001"); + connectSend = false; + } + } + + private void transfer(PSXLinda getpsx, PSXLinda sendpsx) throws IOException { + PSXReply in = getpsx.in(id); + System.out.println("PSXReply "+port1); + while (running) { + if(in.ready()){ + data = in.getData(); + int i = data.getInt(); + data.rewind(); + //outしたbytebufferの変更をこれ以降やっちゃいけない + sendpsx.out(id,data); + + System.out.println("IntData0 "+port1 +i); + fdl1.sync(1); + running = false; + System.out.println("IntData1 "+port1 +i); + break; + } + fdl1.sync(); + } +// assertEquals(4,count); + } + +} + diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/Ring/Server.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/Ring/Server.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,39 @@ +package fdl.test.metaTransfer.Ring; + +import java.io.IOException; + +import fdl.FDLindaServ; + +public class Server extends Thread { + int port1; + int port2; + int set; + private String name; + + public Server(String string, int i, int t, int s) { + port1 = i; + port2 = t; + name = string; + set = s; + } + + public void run(){ + String[] args = {"-p",Integer.toString(port1)}; + System.out.println(name); + switch (set){ + case 0: + try { + FDLServWithSend send = new FDLServWithSend(port1,port2); + send.mainLoop(); + } catch (IOException e) { + e.printStackTrace(); + } + break; + + case 1: + FDLindaServ.main(args); + break; + } + } + +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/Ring/TestSend.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/Ring/TestSend.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,47 @@ +package fdl.test.metaTransfer.Ring; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; + +public class TestSend extends Thread { + PSXLinda psxsend; + FederatedLinda fdlsend; + + public void run(){ + int id = 10; + int port = 10001; + boolean connect = true; + String host = "127.0.0.1"; + ByteBuffer send = ByteBuffer.allocate(1024); + send.putInt(12); + send.flip(); + while(connect){ + try { + sendData(id, port, host, send); + connect = false; + } catch(IOException e) { + try { + Thread.sleep(40); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + } + + } + } + + private void sendData(int id, int port, String host, ByteBuffer send) throws IOException { + fdlsend = FederatedLinda.init(); + + psxsend = fdlsend.open(host,port); + System.out.println("Connect Host1"); + psxsend.out(id, send); + fdlsend.sync(1); + System.out.println("Send Data"); + + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/Ring/TestTransfer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/Ring/TestTransfer.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,29 @@ +package fdl.test.metaTransfer.Ring; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.junit.Test; + +public class TestTransfer { + @Test + public void testTransfer() throws IOException { + int port1 = 10001; + int port2 = 10002; + + Server server1 = new Server("Server1",port1, port2,0); + server1.start(); + + Server server2 = new Server("Server2",port2, port1,1); + server2.start(); + + try { + server2.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + assertEquals(1,1); + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/Ring/TestTransferRing.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/Ring/TestTransferRing.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,40 @@ +package fdl.test.metaTransfer.Ring; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class TestTransferRing { + Server[] servers; + final int serverCount = 3; + final int startPort = 10001; + @Test + public void testTransfer() { + int port = startPort; + + servers = new Server[serverCount]; + + for (int i = 0; i < serverCount; i++) { + servers[i] = new Server("Server"+(i+1),port+i,netporot(port+i),0); + servers[i].start(); + } + +// try { +// servers[3].join(); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } + + + assertEquals(1,1); + } + private int netporot(int i) { + i++; + if(i >= startPort+serverCount) { + return startPort; + } + + return i; + } +} + diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/Ring/TestTransferThree.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/Ring/TestTransferThree.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,22 @@ +package fdl.test.metaTransfer.Ring; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class TestTransferThree { + @Test + public void testTransfer() { + + Server server1 = new Server("Server1", 10001, 10002, 0); + server1.start(); + Server server2 = new Server("Server2", 10002, 10001, 0); + server2.start(); +// Server server3 = new Server("Server3", 10003, 10001, 0); +// server3.start(); + + assertEquals(1,1); + } + +} + diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/Server.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/Server.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,20 @@ +package fdl.test.metaTransfer; + +import fdl.FDLindaServ; + +public class Server extends Thread { + int port; + private String name; + + public Server(String string, int i) { + port = i; + name = string; + } + + public void run(){ + String[] args = {"-p",Integer.toString(port)}; + System.out.println(name); + FDLindaServ.main(args); + } + +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/TestSend.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/TestSend.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,47 @@ +package fdl.test.metaTransfer; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; + +public class TestSend extends Thread { + PSXLinda psxsend; + FederatedLinda fdlsend; + + public void run(){ + int id = 10; + int port = 10001; + boolean connect = true; + String host = "127.0.0.1"; + ByteBuffer send = ByteBuffer.allocate(1024); + send.putInt(12); + send.flip(); + while(connect){ + try { + sendData(id, port, host, send); + connect = false; + } catch(IOException e) { + try { + Thread.sleep(40); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + } + + } + } + + private void sendData(int id, int port, String host, ByteBuffer send) throws IOException { + fdlsend = FederatedLinda.init(); + + psxsend = fdlsend.open(host,port); + System.out.println("Connect Host1"); + psxsend.out(id, send); + fdlsend.sync(1); + System.out.println("Send Data"); + + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/metaTransfer/TestTransfer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/metaTransfer/TestTransfer.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,27 @@ +package fdl.test.metaTransfer; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.junit.Test; + +public class TestTransfer { + @Test + public void testTransfer() throws IOException { + int port1 = 10001; + int port2 = 10002; + +// Server server1 = new Server("Server1",port1); +// server1.start(); +// + Server server2 = new Server("Server2",port2); + server2.start(); + + + FDLServWithSend send = new FDLServWithSend(port1, port2); + send.mainLoop(); + + assertEquals(1,1); + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/topology/FDLindaNode.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/topology/FDLindaNode.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,62 @@ +package fdl.test.topology; + +import java.io.IOException; + +import fdl.FDLindaServ; +import fdl.MetaLinda; +import fdl.MetaEngine; + +/** +* FDLindaNode +* +* @author Kazuki Akamine +* +* Federated Linda の Topology Node +* 接続する機能までを実装 MetaEngine は外部から提供される +* +*/ + +public class FDLindaNode extends FDLindaServ { + // Fields + private MetaLinda ml; + private static int localPort = 10000; + private static String managerHostName; + private final static String usageString + = "Usage: FDLindaNode -manager SERVERNAME"; + + // Constructor + public FDLindaNode(int port) throws IOException { + super(port); + this.ml = new MetaLinda(tupleSpace, this); + } + + @Override public void mainLoop() { + me.mainLoop(); + } + public void setMetaEngine(MetaEngine me) { + this.me = me; + } + public MetaLinda getMetaLinda() { + return ml; + } + + // main routine + public static void main(String[] args) { + for (int i = 0; i < args.length; i++) { + if ("-manager".equals(args[i])) { + managerHostName = args[++i]; + } else { + System.err.println(usageString); + } + } + try { + FDLindaNode node = new FDLindaNode(localPort); + MetaEngine me = new MetaProtocolEngine(node.getMetaLinda(), managerHostName); + node.setMetaEngine(me); + node.mainLoop(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/topology/MetaProtocolEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/topology/MetaProtocolEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,116 @@ +package fdl.test.topology; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; + +import java.nio.ByteBuffer; +import java.util.ArrayList; + +import fdl.MetaEngine; +import fdl.MetaLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + +/** +* MetaProtocolEngine +* +* @author Kazuki Akamine +* +* 接続する機能までを実装した MetaEngine +* これを継承して、具体的な処理を書く +* +*/ + +public class MetaProtocolEngine implements MetaEngine { + // Fields + protected static String lastToken = "null"; + protected static int port = 10000; + protected static int manageId = 60000; + protected PSXLinda manager, psxLocal; + protected ArrayList psxSendServers; + protected MetaLinda fdlMeta; + protected String managerHostName; + protected String localHostName; + + // Constructor + public MetaProtocolEngine(MetaLinda ml, String managerHostName) { + this.fdlMeta = ml; + this.managerHostName = managerHostName; + try { + this.localHostName = InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + e.printStackTrace(); + } + this.psxSendServers = new ArrayList(); + } + + public void mainLoop() { + psxLocal = fdlMeta; + initTopologyManager(); + initSendServer(); + } + + protected void initSendServer() { + sendLocalHostName(); + connectSendServers(); + sendLocalHostName(); + } + + protected void initTopologyManager() { + // Connect to TopologyManager Server + try { + manager = fdlMeta.open(managerHostName, port); + } catch (IOException e) { + // manager は先に立ち上げてから実行する。 + // while で回して再接続 loop にすべき? + e.printStackTrace(); + } + } + + protected void sendLocalHostName() { + // TopologyManager に自分のホストネームを送信して、起動を伝える + ByteBuffer local; + local = ByteBuffer.wrap(localHostName.getBytes()); + manager.out(manageId, local); + try { + manager.sync(1); + } catch (IOException e) { + e.printStackTrace(); + } + } + + protected void connectSendServers() { + // TopologyManager から、送られてくる ConnectServer の hostName を取得して接続 + System.out.println("[DEBUG] MethodCall connectSendServers()"); + while (true) { + PSXReply reply; + reply = psxLocal.in(manageId); + do { + try { + psxLocal.sync(1); + } catch (IOException e) { + e.printStackTrace(); + } + } while (!reply.ready()); + ByteBuffer data = reply.getData(); + String hostName = new String(data.array()); + System.out.println("[DEBUG] GetReply " + hostName); + if (hostName.equals(lastToken)) + break; + connectSendServer(hostName); + } + } + + protected void connectSendServer(String hostName) { + PSXLinda linda; + try { + linda = fdlMeta.open(hostName, port); + psxSendServers.add(linda); + } catch (IOException e) { + e.printStackTrace(); + } + System.out.println("Connect to " + hostName); + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/topology/NodeManager.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/topology/NodeManager.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,93 @@ +package fdl.test.topology; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; + +import fdl.PSXLinda; +import fdl.MetaLinda; + +public class NodeManager { + public String hostName; + public PSXLinda linda; + private MetaLinda mLinda; + private int port; + private int manageId; + private ArrayList waitingNodes; + private ArrayList waitedNodes; +// private ArrayList sendNodes; + + public NodeManager(MetaLinda ml, int port, int manageId) { + this.port = port; + this.manageId = manageId; + this.mLinda = ml; + hostName = null; + waitingNodes = new ArrayList(); + waitedNodes = new ArrayList(); +// sendNodes = new ArrayList(); + } + + public void addConnection(NodeManager node) { + waitingNodes.add(node); + node.waitedNodes.add(this); + } + + public void finishConnection(NodeManager node) { + waitingNodes.remove(node); + node.waitedNodes.remove(this); +// sendNodes.add(node); + } + + public void startUp(String hostName) { + // 起動 + this.hostName = hostName; + try { + linda = mLinda.open(hostName, port); + } catch (IOException e) { + e.printStackTrace(); + } + // 起動待ちのノードに通知 + connectWaitedNodes(); + } + + public void connectWaitedNodes() { + for (int i = 0; i < waitedNodes.size(); i++) { + NodeManager node = waitedNodes.get(i); + if (node.isRunning()) { + node.connect(this); + node.finishConnection(this); + if (waitingNodes.contains(node)) { + connect(node); + finishConnection(node); + } + } + } + for (int i = 0; i < waitingNodes.size(); i++) { + NodeManager node = waitingNodes.get(i); + if (node.isRunning()) { + connect(node); + finishConnection(node); + if (node.waitingNodes.contains(this)) { + node.connect(this); + node.finishConnection(this); + } + } + } + } + + public void connect(NodeManager node) { + ByteBuffer data = ByteBuffer.wrap(node.hostName.getBytes()); + linda.out(manageId, data); + try { + linda.sync(1); + System.out.println("[DEBUG] SendConnectTo: " + hostName + " to " + node.hostName); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public boolean isRunning() { + return hostName != null; + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/topology/TopologyManager.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/topology/TopologyManager.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,40 @@ +package fdl.test.topology; + +import java.io.IOException; + +import fdl.MetaEngine; + +/** +* TopologyManager +* +* @author Kazuki Akamine +* +* FDLindaNode の Topology を管理する Server +* +*/ + +public class TopologyManager { + private static int localPort = 10000; + private static int nodeNum = 2; + private static String usageString + = "TopologyManager -nodes NODENUM"; + + public static void main(String[] args) { + for (int i = 0; i < args.length; i++) { + if ("-nodes".equals(args[i])) { + nodeNum = Integer.parseInt(args[++i]); + } else { + System.err.println(usageString); + } + } + try { + FDLindaNode manager = new FDLindaNode(localPort); + MetaEngine me = new TopologyManagerEngine(manager.getMetaLinda(), nodeNum); + manager.setMetaEngine(me); + manager.mainLoop(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/topology/TopologyManagerEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/topology/TopologyManagerEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,113 @@ +package fdl.test.topology; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.MetaEngine; +import fdl.MetaLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + +/** +* TopologyManagerEngine +* +* @author Kazuki Akamine +* +* FDLindaNode の Topology を管理する Server の MetaEngine +* TopologyManager の具体的な実装 +* +*/ + +public class TopologyManagerEngine implements MetaEngine { + protected static String lastToken = "null"; + protected static int port = 10000; + protected static int manageId = 60000; + protected PSXLinda manager; + protected MetaLinda fdlMeta; + protected int nodeNum; // 後々は、nodelist から自動で取得したい + protected NodeManager[] nodes; + + // Constructor + public TopologyManagerEngine(MetaLinda ml, int nodeNum) { + this.fdlMeta = ml; + this.nodeNum = nodeNum; + this.nodes = new NodeManager[this.nodeNum]; + for (int i = 0; i < nodes.length; i++) { + this.nodes[i] = new NodeManager(fdlMeta, port, manageId); + } + } + + public void mainLoop() { + manager = fdlMeta; + makeTopology(); + } + + protected void makeTopology() { + makeConnection(); + acceptNewNode(); + sendLastToken(); + checkConnection(); + } + + // これを継承して、 Topology を形成 + // 最終的には外部XMLを読み込んで接続するようにする + protected void makeConnection() { + // 接続を定義 + nodes[0].addConnection(nodes[1]); + nodes[1].addConnection(nodes[0]); + } + + protected void acceptNewNode() { + // 起動状況を確認しつつ、接続命令を送信 + // nodes の数だけ新規参入 node を待つ。 + for (int i = 0; i < nodes.length; i++) { + PSXReply reply; + reply = manager.in(manageId); + do { + try { + manager.sync(1); + } catch (IOException e) { + e.printStackTrace(); + } + } while (!reply.ready()); + ByteBuffer data = reply.getData(); + String hostName = new String(data.array()); + System.out.println("[DEBUG] GetNodeName: " + hostName); + nodes[i].startUp(hostName); + } + } + + protected void sendLastToken() { + ByteBuffer lastTokenBB = ByteBuffer.wrap(lastToken.getBytes()); + for (int i = 0; i < nodes.length; i++) { + // 参加ノードに実験開始を告知する ("null"を送る) + nodes[i].linda.out(manageId, lastTokenBB); + System.out.println("[DEBUG] SendMsg: " + lastToken + " to " + nodes[i].hostName); + + try { + nodes[i].linda.sync(1); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + protected void checkConnection() { + for (int i = 0; i < nodes.length; i++) { + PSXReply reply; + reply = manager.in(manageId); + do { + try { + manager.sync(1); + } catch (IOException e) { + e.printStackTrace(); + } + } while (!reply.ready()); + ByteBuffer data = reply.getData(); + String ack = new String(data.array()); + System.out.println("[DEBUG] ConnectedHost: " + ack); + } + System.out.println("[DEBUG] AllConnected"); + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/topology/ring/FDLindaRingNode.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/topology/ring/FDLindaRingNode.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,49 @@ +package fdl.test.topology.ring; + +import java.io.IOException; +import fdl.MetaEngine; +import fdl.test.topology.*; + +/** +* FDLindaRingNode +* +* @author Kazuki Akamine +* +* Federated Linda の Ring 用 Node +* Ring 用の MetaEngine を持たせる。 +* +*/ + +public class FDLindaRingNode { + // Fields + private static int localPort = 10000; + private static String managerHostName; + private static String relayNumString; + private static int relayNum; + private final static String usageString + = "Usage: FDLindaRingNode -manager SERVERNAME"; + + // main routine + public static void main(String[] args) { + for (int i = 0; i < args.length; i++) { + if ("-manager".equals(args[i])) { + managerHostName = args[++i]; + } else if ("-relay".equals(args[i])) { + relayNumString = args[++i]; + } else { + System.err.println(usageString); + } + } + relayNum = Integer.parseInt(relayNumString); + + try { + FDLindaNode node = new FDLindaNode(localPort); + MetaEngine me = new RingMetaProtocolEngine(node.getMetaLinda(), managerHostName, relayNum); + node.setMetaEngine(me); + node.mainLoop(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/topology/ring/RingMetaProtocolEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/topology/ring/RingMetaProtocolEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,102 @@ +package fdl.test.topology.ring; + +import java.io.IOException; +import java.nio.ByteBuffer; +//import java.text.SimpleDateFormat; +import java.util.Date; + +import fdl.MetaLinda; +import fdl.PSXLinda; +import fdl.PSXReply; +import fdl.test.topology.MetaProtocolEngine; + +/** +* RingMetaProtocolEngine +* +* @author Kazuki Akamine +* +* Ring 接続実験用の MetaProtocolEngine +* Ring 接続実験の具体的な処理を記述する。 +* +*/ + +public class RingMetaProtocolEngine extends MetaProtocolEngine { + private int relayNum; + private static int relayId = 10; + private Date startTime, endTime; + //private SimpleDateFormat DF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); + public RingMetaProtocolEngine(MetaLinda ml, String managerHostName, int relayNum) { + super(ml, managerHostName); + this.relayNum = relayNum; + startTime = null; + endTime = null; + } + + @Override public void mainLoop() { + // 接続処理 + super.mainLoop(); + // Ring 実験開始 + relayTuple(relayId); + } + + private void relayTuple(int tupleId) { + while (true) { + ByteBuffer data = receiveToken(tupleId); + if (startTime == null) { + startTime = new Date(); + } + if (relayNum == 0) { + String token = new String(data.array()); + if (!token.equals(lastToken)) { + // TODO: 実験結果をManagerに伝えるなどの処理 + sendResult(); + System.out.println("[Ring] relay finished: " + token); + // 実験終了を各ノードにリレーで伝える + sendToken(tupleId, ByteBuffer.wrap(lastToken.getBytes())); + } + return; + } + sendToken(tupleId, data); + System.out.println("[DEBUG] Relay..."); + relayNum--; + } + } + + private void sendResult() { + this.endTime = new Date(); + Long resultTime = new Long(endTime.getTime() - startTime.getTime()); + ByteBuffer data = ByteBuffer.wrap(resultTime.toString().getBytes()); + manager.out(relayId, data); + try { + manager.sync(1); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private ByteBuffer receiveToken(int tupleId) { + PSXReply reply = psxLocal.in(tupleId); + do { + try { + psxLocal.sync(1); + } catch (IOException e) { + e.printStackTrace(); + } + } while (!reply.ready()); + ByteBuffer data = reply.getData(); + return data; + } + + private void sendToken(int tupleId, ByteBuffer data) { + for (int i = 0; i < psxSendServers.size(); i++) { + PSXLinda linda = psxSendServers.get(i); + linda.out(tupleId, data); + try { + linda.sync(1); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/topology/ring/RingTopologyManager.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/topology/ring/RingTopologyManager.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,41 @@ +package fdl.test.topology.ring; + +import java.io.IOException; + +import fdl.MetaEngine; +import fdl.test.topology.FDLindaNode; + +/** +* RingTopologyManager +* +* @author Kazuki Akamine +* +* FDLindaNode の Topology を管理する Server +* Ring 実験用の Main Class +* +*/ + +public class RingTopologyManager { + private static int localPort = 10000; + private static int nodeNum; + private static String usageString + = "RingTopologyManager -nodes NODENUM"; + + public static void main(String[] args) { + for (int i = 0; i < args.length; i++) { + if ("-nodes".equals(args[i])) { + nodeNum = Integer.parseInt(args[++i]); + } else { + System.err.println(usageString); + } + } + try { + FDLindaNode manager = new FDLindaNode(localPort); + MetaEngine me = new RingTopologyManagerEngine(manager.getMetaLinda(), nodeNum); + manager.setMetaEngine(me); + manager.mainLoop(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/topology/ring/RingTopologyManagerEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/topology/ring/RingTopologyManagerEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,61 @@ +package fdl.test.topology.ring; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.MetaLinda; +import fdl.PSXReply; +import fdl.test.topology.TopologyManagerEngine; + +public class RingTopologyManagerEngine extends TopologyManagerEngine { + private int relayId = 10; + + // Constructor + public RingTopologyManagerEngine(MetaLinda ml, int nodeNum) { + super(ml, nodeNum); + } + + public void mainLoop() { + super.mainLoop(); + startRelay(); + endRelay(); + } + + protected void makeTopology() { + super.makeTopology(); + } + + @Override protected void makeConnection() { + // Ring 状の接続を定義 + for (int i = 0; i < nodes.length; i++) { + nodes[i].addConnection(nodes[(i+1)%nodes.length]); + } + } + + private void startRelay() { + String relayString = "test"; + ByteBuffer data = ByteBuffer.wrap(relayString.getBytes()); + nodes[0].linda.out(relayId, data); + try { + nodes[0].linda.sync(1); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void endRelay() { + PSXReply reply; + reply = manager.in(relayId); + do { + try { + manager.sync(1); + } catch (IOException e) { + e.printStackTrace(); + } + } while (!reply.ready()); + ByteBuffer data = reply.getData(); + String resultData = new String(data.array()); + System.out.println("[DEBUG] RelayTime: " + resultData); + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/ProtocolEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/ProtocolEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,74 @@ +package fdl.test.transfer; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + + +public class ProtocolEngine extends Thread{ + private PSXLinda psx; + private String name; + FederatedLinda fdl1; + String host = "127.0.0.1"; + int port1 = 10001; + int port2 = 10002; + private int id = 10; + private PSXLinda psx1; + private boolean running = true; + private ByteBuffer data2 = ByteBuffer.allocate(10); + + public ProtocolEngine(String string, int port1, int port2) { + this.name = string; + this.port1 = port1; + this.port2 = port2; + } + + public void run(){ + fdl1 = FederatedLinda.init(); + try { + System.out.println(name); + psx = fdl1.open(host,port1); + System.out.println("Connect Host1"); + psx1 = fdl1.open(host,port2); + System.out.println("Connect Host2"); + // Host1にデータを送信する。 + testSend(psx); + // psxにデータを用意 + transfer(psx,psx1); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void testSend(PSXLinda psx2) throws IOException { + ByteBuffer send = ByteBuffer.allocate(10); + send.putInt(12); + send.flip(); + psx2.out(id, send); + psx2.sync(1); + } + + + private void transfer(PSXLinda getpsx, PSXLinda sendpsx) throws IOException { + PSXReply in = getpsx.in(id); + while (running) { + System.out.println(in.ready()); + if(in.ready()){ + //psx1にデータを書き出し + data2 = in.getData(); + sendpsx.out(id,data2); + //runningフラグをfalseする + running = false; + fdl1.sync(0); + break; + } + fdl1.sync(); + } + + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/Server.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/Server.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,20 @@ +package fdl.test.transfer; + +import fdl.FDLindaServ; + +public class Server extends Thread{ + int port; + private String name; + + public Server(String string, int i) { + port = i; + name = string; + } + + public void run(){ + String[] args = {"-p",Integer.toString(port)}; + System.out.println(name); + FDLindaServ.main(args); + } + +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/TestSend.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/TestSend.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,33 @@ +package fdl.test.transfer; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; + +public class TestSend extends Thread { + PSXLinda psxsend; + FederatedLinda fdlsend; + + public void run(){ + int id = 10; + int port = 10001; + String host = "127.0.0.1"; + ByteBuffer send = ByteBuffer.allocate(1024); + send.putInt(12); + send.flip(); + fdlsend = FederatedLinda.init(); + try{ + psxsend = fdlsend.open(host,port); + System.out.println("Connect Host1"); + psxsend.out(id, send); + fdlsend.sync(); + System.out.println("Send Data"); + }catch (IOException e) { + System.out.println("例外:" + e); + } + + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/TestTransfer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/TestTransfer.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,25 @@ +package fdl.test.transfer; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class TestTransfer { + @Test + public void testTransfer() { + int port1 = 10001; + int port2 = 10002; + Server server1 = new Server("Server1",port1); + server1.start(); + Server server2 = new Server("Server2",port2); + server2.start(); + ProtocolEngine pe = new ProtocolEngine("ProtocolEngine",port1,port2); + pe.start(); + try { + pe.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + assertEquals(1,1); + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/cluster/FDLServWithSendMeta.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/cluster/FDLServWithSendMeta.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,91 @@ +package fdl.test.transfer.cluster; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; + +import fdl.FDLindaServ; +import fdl.MetaLinda; + + +public class FDLServWithSendMeta extends FDLindaServ { + + public FDLServWithSendMeta(int port) throws IOException { + super(port); + } + + static String nextHost = null; + private static int localport = 10000; + static int chknum; + private static String bufstring; + private static int bufsize; + private static String txt; + private static int ring; + + @Override public void mainLoop() { + MetaLinda ml = new MetaLinda(tupleSpace, this); + MetaProtocolEngine mpe = new MetaProtocolEngine(ml, nextHost, chknum, bufsize, txt); + mpe.mainLoop(); + } + + public static void main(String[] args){ + for (int k=0; k "+start); + } catch (IOException e) { + e.printStackTrace(); + } + } + boolean connect = true; + while(connect){ + try { + initConnect(); + transfer = DF.format(new Date()); + transferlong = new Date().getTime(); + System.out.println("transfer Time => "+transfer); + for(int l = 0; l < 1000; l++) { + transfer(); + } + dataChk(); + write(); + connect = false; + } catch (IOException e) { + try { + Thread.sleep(40); + } catch (InterruptedException e1) { + } + } + } + } + + private void initConnect(){ + boolean connectpsx = true; + while(connectpsx){ + try { + psxsend = fdlmeta.open(host, port); + connectpsx = false; + } catch (IOException e) { + try { + Thread.sleep(40); + } catch (InterruptedException e1) { + e1.printStackTrace(); + } + } + } + } + + private void sendData() throws IOException{ + boolean connectSend = true; + ByteBuffer send = ByteBuffer.allocate(bufsize); + byte[] fdata = new byte[bufsize]; + // fdata = InetAddress.getLocalHost().getAddress(); + for(int n=0; n < fdata.length; n++ ){ + fdata[n] = 1; + } + send.put(fdata); + send.flip(); + while(connectSend){ + psxget.out(id, send); + psxget.sync(1); + System.out.println("Send Data"); + connectSend = false; + } + } + + public void transfer() throws IOException { + ByteBuffer data = ByteBuffer.allocate(bufsize); + boolean running = true; + PSXReply in = psxget.in(id); + while (running) { + if(in.ready()){ + data = in.getData(); + psxsend.out(id,data); + System.out.println("connect to => "+host); + psxsend.sync(1); + running = false; + break; + } + fdlmeta.sync(); + } + } + + public void dataChk() throws IOException{ + fdlmeta.sync(1); + boolean running2 = true; + // ByteBuffer data2 = ByteBuffer.allocate(bufsize); + PSXReply in2 = psxget.in(id); + // byte[] fdata2 = new byte[bufsize]; + // byte[] fdata3 = new byte[bufsize]; + // fdata = InetAddress.getLocalHost().getAddress(); + // for(int n=0; n < fdata2.length; n++ ){ + // fdata2[n] = 1; + // } + while (running2) { + psxget.sync(1); + if(in2.ready()) { + // data2 = in2.getData(); + // data2.get(fdata3); + // if (fdata2 == fdata3){ + time = DF.format(new Date()); + timelong = new Date().getTime(); + System.out.println("Around Time => "+time); + // } + running2 = false; + break; + } + } + } + + + public void write() throws IOException{ + long result = (timelong - transferlong); + String diff = String.valueOf(result); + File read = new File("resultTime"+bufsize+"_"+txt+".txt"); + read.createNewFile(); + FileWriter filewrite = new FileWriter(read); + if (start != "null"){ + filewrite.write("ServerStart => "+start+"\r\n"); + } + if (transfer != "null") { + filewrite.write("TransferTime => "+transfer+"\r\n"); + } + if (time != "null"){ + filewrite.write("AroundTime => "+time+"\r\n"); + } + if (diff != "null"){ + filewrite.write("DiffTime => "+diff+"\r\n"); + } + filewrite.close(); + } +} + diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/cluster/ProtocolEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/cluster/ProtocolEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,147 @@ +package fdl.test.transfer.cluster; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.net.InetAddress; +import java.nio.ByteBuffer; +import java.text.SimpleDateFormat; +import java.util.Date; + +import fdl.FederatedLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + + +public class ProtocolEngine extends Thread{ + static int id = 10; + static FederatedLinda fdl; + static PSXLinda getpsx; + static PSXLinda sendpsx; + static int port = 10000; + String getHost = null; + String sendHost = null; + private int chknum; + private int bufsize; + private String txt; + SimpleDateFormat DF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); + private String time; + private long timelong; + private String start; + private String transfer; + private long transferlong; + + public ProtocolEngine(String gethost, String sendhost, int chknum, int bufsize, String txt) { + this.getHost = gethost; + this.sendHost = sendhost; + this.chknum = chknum; + this.bufsize = bufsize; + this.txt = txt; + } + + public void run(){ + fdl = FederatedLinda.init(); + try { + getpsx = fdl.open(getHost,port); + System.out.println("Connect Host1"); + sendpsx = fdl.open(sendHost,port); + System.out.println("Connect Host2"); + // Host1にデータを送信する。 + if(chknum == 1){ + testSend(getpsx); + start = DF.format(new Date()); + System.out.println("Start Time => "+start); + } + // psxにデータを用意 + transfer(getpsx,sendpsx); + dataChk(); + write(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void write() throws IOException { + long result = (timelong - transferlong); + String diff = String.valueOf(result); + File read = new File("resultTime"+bufsize+"_"+txt+".txt"); + read.createNewFile(); + FileWriter filewrite = new FileWriter(read); + if (start != "null"){ + filewrite.write("ServerStart => "+start+"\r\n"); + } + if (transfer != "null") { + filewrite.write("TransferTime => "+transfer+"\r\n"); + } + if (time != "null"){ + filewrite.write("AroundTime => "+time+"\r\n"); + } + if (diff != "null"){ + filewrite.write("DiffTime => "+diff+"\r\n"); + } + filewrite.close(); + } + + private void dataChk() throws IOException { + fdl.sync(1); + boolean running2 = true; + ByteBuffer data3 = ByteBuffer.allocate(bufsize); + PSXReply in2 = getpsx.in(id); + int localhost2 = InetAddress.getLocalHost().hashCode(); + while (running2) { + getpsx.sync(1); + if(in2.ready()) { + data3 = in2.getData(); + int i = data3.getInt(); + if (i == localhost2){ + time = DF.format(new Date()); + timelong = new Date().getTime(); + System.out.println("Around Time => "+time); + } + running2 = false; + break; + } + } + + } + + private void testSend(PSXLinda psx2) throws IOException { + boolean connectSend = true; + ByteBuffer send = ByteBuffer.allocate(bufsize); + int localhost = InetAddress.getLocalHost().hashCode(); + send.putInt(localhost); + send.flip(); + while(connectSend){ + psx2.out(id, send); + psx2.sync(1); + System.out.println("Send Data"); + connectSend = false; + } + } + + + private void transfer(PSXLinda getpsx, PSXLinda sendpsx) throws IOException { + ByteBuffer data2 = ByteBuffer.allocate(bufsize); + PSXReply in = getpsx.in(id); + boolean running = true; + while (running) { + if(in.ready()){ + //psx1にデータを書き出し + data2 = in.getData(); + sendpsx.out(id,data2); + //runningフラグをfalseする + running = false; + transfer = DF.format(new Date()); + transferlong = new Date().getTime(); + System.out.println("transfer Time => "+transfer); + System.out.println("connect to => "+sendHost); + sendpsx.sync(1); + break; + } + fdl.sync(); + } + + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/cluster/ProtocolEngineMain.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/cluster/ProtocolEngineMain.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,72 @@ +package fdl.test.transfer.cluster; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.text.SimpleDateFormat; +import java.util.Date; + +import fdl.FederatedLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + +public class ProtocolEngineMain { + static int id = 10; + static FederatedLinda fdl; + static PSXLinda getpsx; + static PSXLinda sendpsx; + static int port = 10000; + private static String getHost = null; + private static String sendHost = null; + + public static void main(String[] args) { + for (int i=0; i "+i); + //runningフラグをfalseする + running = false; + sendpsx.sync(1); + System.out.println("Transfer Data"); + break; + } + SimpleDateFormat DF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); + System.out.println(DF.format(new Date())); + fdl.sync(); + } + + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/cluster/Server.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/cluster/Server.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,16 @@ +package fdl.test.transfer.cluster; + +import fdl.FDLindaServ; + +public class Server extends Thread{ + int port; + + public Server() { + } + + public void run(){ + String[] args = {"-p",Integer.toString(port)}; + FDLindaServ.main(args); + } + +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/cluster/ServerMain.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/cluster/ServerMain.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,12 @@ +package fdl.test.transfer.cluster; + +import fdl.FDLindaServ; + +public class ServerMain{ + public static void main(String[] args){ + int port = 10000; + String[] args1 = {"-p",Integer.toString(port)}; + FDLindaServ.main(args1); + } + +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/cluster/TestGet.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/cluster/TestGet.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,48 @@ +package fdl.test.transfer.cluster; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + + +public class TestGet extends Thread { + private PSXLinda psxget; + private FederatedLinda fdlget; + private int port; + String host = "127.0.0.1"; + private ByteBuffer data = ByteBuffer.allocate(1024); + + public TestGet(int port1) { + this.port = port1; + } + + public void run(){ + int id = 10; + int i; + fdlget = FederatedLinda.init(); + try { + System.out.println("TestGet Start"); + psxget = fdlget.open(host, port); + System.out.println("Host1 connected"); + //getにidのタプルを取り出す + PSXReply dataGet = psxget.in(id); + System.out.println("dataget"); + System.out.println(dataGet.ready()); + if(dataGet.ready()){ + System.out.println(dataGet); + data = dataGet.getData(); + fdlget.sync(1); + i = data.getInt(); + System.out.println(i); + } + } catch (IOException e) { + try { + Thread.sleep(10); + } catch (InterruptedException e1) { + } + } + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/cluster/TestSend.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/cluster/TestSend.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,46 @@ +package fdl.test.transfer.cluster; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; + +public class TestSend { + static PSXLinda psxsend; + static FederatedLinda fdlsend; + private static int port = 10000; + + public static void main(String[] args){ + int id = 10; + int i; + String host = "cls001.cs.ie.u-ryukyu.ac.jp"; + ByteBuffer send = ByteBuffer.allocate(1024); + send.putInt(12); + send.flip(); + i = send.getInt(); + send.rewind(); + fdlsend = FederatedLinda.init(); + boolean connect = true; + while(connect) { + try{ + System.out.println("TestSend Start"); + psxsend = fdlsend.open(host,port); + System.out.println("Set Data = " +i); + System.out.println("Connect Host1"); + psxsend.out(id, send); + System.out.println("regist Que"); + fdlsend.sync(); + System.out.println("Send Data"); + connect = false; + }catch (IOException e) { + try { + Thread.sleep(40); + } catch (InterruptedException e1) { + } + } + } + } + + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/three/ProtocolEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/three/ProtocolEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,82 @@ +package fdl.test.transfer.three; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + + +public class ProtocolEngine extends Thread{ + private PSXLinda psx; + private String name; + FederatedLinda fdl1; + String host = "127.0.0.1"; + int port1; + int port2; + private int id = 10; + private PSXLinda psx1; + private boolean running = true; + private ByteBuffer data2 = ByteBuffer.allocate(10); + private int count = 1; + + public ProtocolEngine(String string, int port1, int port2) { + this.name = string; + this.port1 = port1; + this.port2 = port2; + } + + public void run(){ + fdl1 = FederatedLinda.init(); + boolean connect = true; + while(connect){ + try { + initConnect(); + transfer(); + connect = false; + } catch (IOException e) { + try { + Thread.sleep(40); + } catch (InterruptedException e1) { + } + } + } + } + + private void initConnect() throws IOException { + System.out.println(name); + psx = fdl1.open(host,port1); + System.out.println("Connect "+port1); + psx1 = fdl1.open(host,port2); + System.out.println("Connect "+port2); + } + + private void transfer() throws IOException { + PSXReply in = psx.in(id); + System.out.println("PSXReply "+port1 +": "+port2 +": "); + while (running) { + if(in.ready()){ + data2 = in.getData(); + int i = data2.getInt(); + data2.rewind(); + //outしたbytebufferの変更をこれ以降やっちゃいけない + psx1.out(id,data2); + + System.out.println("IntData0 "+port1 +": "+port2 +": " +i); + fdl1.sync(1); + if (count++>3) { + running = false; + break; + } + System.out.println("IntData1 "+port1 +": "+port2 +": " +i); + } + fdl1.sync(); + } + assertEquals(4,count); + } + + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/three/Server.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/three/Server.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,20 @@ +package fdl.test.transfer.three; + +import fdl.FDLindaServ; + +public class Server extends Thread { + int port; + private String name; + + public Server(String string, int i) { + port = i; + name = string; + } + + public void run(){ + String[] args = {"-p",Integer.toString(port)}; + System.out.println(name+"start"); + FDLindaServ.main(args); + } + +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/three/TestGet.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/three/TestGet.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,55 @@ +package fdl.test.transfer.three; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + + +public class TestGet extends Thread { + PSXLinda psxget; + FederatedLinda fdlget; + private int port; + String host = "127.0.0.1"; + private ByteBuffer data = ByteBuffer.allocate(10); + + public TestGet(int port1) { + this.port = port1; + } + + public void run(){ + int id = 10; + int i; + fdlget = FederatedLinda.init(); + boolean connecttest = true; + while(connecttest){ + try { + getData(id); + i = data.getInt(); + System.out.println(i); + connecttest = false; + } catch (IOException e) { + e.printStackTrace(); + connecttest = true; + } + } + } + + private void getData(int id) throws IOException { + psxget = fdlget.open(host, port); + PSXReply get = psxget.in(id); + boolean running = false; + while(running){ + if(get.ready()){ + data = get.getData(); + running = false; + fdlget.sync(0); + break; + } + fdlget.sync(); + } + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/three/TestSend.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/three/TestSend.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,48 @@ +package fdl.test.transfer.three; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; + +public class TestSend extends Thread { + PSXLinda psxsend; + FederatedLinda fdlsend; + private int port; + + public TestSend(int port1) { + this.port = port1; + } + + public void run(){ + int id = 10; + int i; + String host = "127.0.0.1"; + ByteBuffer send = ByteBuffer.allocate(1024); + send.putInt(12); + send.flip(); + i = send.getInt(); + send.rewind(); + fdlsend = FederatedLinda.init(); + boolean connect = true; + while(connect) { + try{ + psxsend = fdlsend.open(host,port); + System.out.println("Set Data = " +i); + System.out.println("Connect Host1"); + psxsend.out(id, send); + System.out.println("regist Que"); + fdlsend.sync(1); + System.out.println("Send Data"); + connect = false; + }catch (IOException e) { + try { + Thread.sleep(20); + } catch (InterruptedException e1) { + } + } + } + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/three/TestTransfer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/three/TestTransfer.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,52 @@ +package fdl.test.transfer.three; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + + +public class TestTransfer { + Server[] servers; + ProtocolEngine[] engines; + final int serverCount = 3; + final int startPort = 10011; + @Test + public void testTransfer() { + int port = startPort; + servers = new Server[serverCount]; + engines = new ProtocolEngine[serverCount]; + + for (int i = 0; i < serverCount; i++) { + servers[i] = new Server("Server"+(i+1),port+i); + servers[i].start(); + } + + TestSend send = new TestSend(startPort); + send.start(); + try{ + send.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + for (int i = 0; i < serverCount; i++) { + engines[i] = new ProtocolEngine("ProtocolEngine "+(i+1) +":port " +(port+i) +":port "+(netporot(port+i)),port+i,netporot(port+i)); + engines[i].start(); + } + try { + for (ProtocolEngine e: engines){ + e.join(); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + assertEquals(1,1); + } + private int netporot(int i) { + i++; + if(i >= startPort+serverCount) { + return startPort; + } + return i; + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/two/ProtocolEngine.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/two/ProtocolEngine.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,67 @@ +package fdl.test.transfer.two; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + + +public class ProtocolEngine extends Thread{ + private static PSXLinda psx; + private static String name; + static FederatedLinda fdl1; + static String host = "127.0.0.1"; + static int port1 = 10001; + static int port2 = 10002; + private static int id = 10; + private static PSXLinda psx1; + private static boolean running; + private static ByteBuffer data2 = ByteBuffer.allocate(10); + + public static void main(String[] args){ + fdl1 = FederatedLinda.init(); + try { + System.out.println(name); + psx = fdl1.open(host,port1); + System.out.println("Connect Host1"); + psx1 = fdl1.open(host,port2); + System.out.println("Connect Host2"); + // Host1にデータを送信する。 + testSend(psx); + // psxにデータを用意 + transfer(psx,psx1); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static void testSend(PSXLinda psx2) throws IOException { + ByteBuffer send = ByteBuffer.allocate(10); + send.putInt(12); + send.flip(); + psx2.out(id, send); + psx2.sync(); + } + + + private static void transfer(PSXLinda psx2, PSXLinda psx12) throws IOException { + PSXReply in = psx2.in(id); + while (running) { + if(in.ready()){ + //psx1にデータを書き出し + data2 = in.getData(); + psx12.out(id,data2); + //runningフラグをfalseする + running = false; + fdl1.sync(0); + break; + } + fdl1.sync(); + } + + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/two/Server.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/two/Server.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,20 @@ +package fdl.test.transfer.two; + +import fdl.FDLindaServ; + +public class Server extends Thread { + int port; + private String name; + + public Server(String string, int i) { + port = i; + name = string; + } + + public void run(){ + String[] args = {"-p",Integer.toString(port)}; + System.out.println(name); + FDLindaServ.main(args); + } + +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/two/TestGet.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/two/TestGet.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,44 @@ +package fdl.test.transfer.two; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + + +public class TestGet extends Thread { + private static PSXLinda psxget; + private static FederatedLinda fdlget; + private static int port = 10001; + static String host = "127.0.0.1"; + private static ByteBuffer data = ByteBuffer.allocate(1024); + + public static void main(String[] args){ + int id = 10; + int i; + fdlget = FederatedLinda.init(); + try { + System.out.println("TestGet Start"); + psxget = fdlget.open(host, port); + System.out.println("Host1 connected"); + //getにidのタプルを取り出す + PSXReply dataGet = psxget.in(id); + System.out.println("dataget"); + System.out.println(dataGet.ready()); + if(dataGet.ready()){ + System.out.println(dataGet); + data = dataGet.getData(); + fdlget.sync(1); + i = data.getInt(); + System.out.println(i); + } + } catch (IOException e) { + try { + Thread.sleep(10); + } catch (InterruptedException e1) { + } + } + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/two/TestSend.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/two/TestSend.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,50 @@ +package fdl.test.transfer.two; + +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; + +public class TestSend extends Thread { + PSXLinda psxsend; + FederatedLinda fdlsend; + private int port; + + public TestSend(int port1) { + this.port = port1; + } + + public void run(){ + int id = 10; + int i; + String host = "127.0.0.1"; + ByteBuffer send = ByteBuffer.allocate(1024); + send.putInt(12); + send.flip(); + i = send.getInt(); + send.rewind(); + fdlsend = FederatedLinda.init(); + boolean connect = true; + while(connect) { + try{ + System.out.println("TestSend Start"); + psxsend = fdlsend.open(host,port); + System.out.println("Set Data = " +i); + System.out.println("Connect Host1"); + psxsend.out(id, send); + System.out.println("regist Que"); + fdlsend.sync(1); + System.out.println("Send Data"); + connect = false; + }catch (IOException e) { + try { + Thread.sleep(40); + } catch (InterruptedException e1) { + } + } + } + } + + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test/transfer/two/TestTransfer.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test/transfer/two/TestTransfer.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,21 @@ +package fdl.test.transfer.two; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class TestTransfer { + @Test + public void testTransfer() throws InterruptedException { + int port = 10001; + Server server = new Server("Server1",port); + server.start(); + server.join(); + TestSend send = new TestSend(port); + send.start(); + + send.join(); + + assertEquals(1,1); + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test2/CountTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test2/CountTest.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,42 @@ +package fdl.test2; + +class CountA implements Runnable { + + public void run() { + for (int i=0; i <= 5; i++) { + System.out.println("A: " + i); + } + } +} + +class CountB implements Runnable { + + public void run() { + for (int i=5; i >= 0; i--) { + System.out.println(" B: " + i); + } + } +} + +class CountTest { + public static void main(String[] args) { + // ランナブルクラスのインスタンス化 + CountA runA = new CountA(); + CountB runB = new CountB(); + System.out.println("Runnable Class のインスタンス化終了"); + + // スレッドのインスタンス化 + Thread threadA = new Thread(runA); + Thread threadB = new Thread(runB); + System.out.println("Thread へ受け渡し終了"); + + // スレッドの開始 + threadA.start(); + threadB.start(); + System.out.println("Thread の start() 終了"); + System.out.println("適時自動的に run() が実行される"); + + + } +} + diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test2/Server.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test2/Server.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,35 @@ +package fdl.test2; + +import java.io.IOException; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.Date; + +public class Server extends Thread{ + static int Port = 10007; + + public void run(){ + try { + ServerSocket server = new ServerSocket(Port); + Socket sock =null; + System.out.println("Server Start"); + sock = server.accept(); + System.out.println("Connect"); + PrintWriter ps = new PrintWriter(sock.getOutputStream()); + Date d = new Date(); + ps.print(d + "\r\n"); + ps.flush(); + sock.close(); // クライアントからの接続を切断 + System.out.println("Connection Closed"); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public static void main(String[] args) { + Server sv = new Server(); + sv.start(); + } +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test2/TestRead.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test2/TestRead.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,26 @@ +package fdl.test2; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; + +public class TestRead { + + public static void main(String[] args) { + try { + File inputFile = new File(args[0]); + FileReader in = new FileReader(inputFile); + BufferedReader br = new BufferedReader(in); + String line; + while ((line = br.readLine()) != null) { + System.out.println(line); + } + br.close(); + in.close(); + } catch (IOException e) { + System.out.println(e); + } + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test2/TestRing.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test2/TestRing.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,51 @@ +package fdl.test2; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.nio.ByteBuffer; + +import fdl.FederatedLinda; +import fdl.PSXLinda; +import fdl.PSXReply; + +public class TestRing { + static int id; + public static void main(String args[]){ + + try{ + FederatedLinda fdl; + PSXLinda psx; + String host = "127.0.0.1"; + PSXReply r; + + FileReader in = new FileReader("nodelist"); + BufferedReader br = new BufferedReader(in); + String line; + + while ((line = br.readLine()) != null) { + int i1 = Integer.parseInt(line); + fdl = FederatedLinda.init(); + psx = fdl.open(host,i1); + r = psx.in(65535); + fdl.sync(1); + + ByteBuffer data = ByteBuffer.allocate(10); + data.putInt(10); + data.flip(); + + psx.out(1,data); + while(!r.ready()){ + psx.sync(); + } + } + br.close(); + in.close(); + + + }catch (IOException e) { + System.err.println("Communication failure."); + } + + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test2/client.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test2/client.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,26 @@ +package fdl.test2; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.Socket; + +public class client { + public static void main(String arg[]) throws IOException{ + String www = arg[0]; + int port = 10007; + Socket sock; + BufferedReader dis; +// PrintWriter ps; + sock = new Socket(www,port); + dis = new BufferedReader(new InputStreamReader(sock.getInputStream())); +// ps = new PrintWriter(sock.getOutputStream(),true); +// ps.println("Get"+arg[1]); +// String s = null; +// while((s = dis.readLine()) != null){ + System.out.println(dis); +// } + sock.close(); + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 src/fdl/test2/nodelist --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/fdl/test2/nodelist Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,2 @@ +10000 +10001 diff -r 1bcc0070c2f6 -r 226c97efb693 tools/Linda_library/Makefile --- a/tools/Linda_library/Makefile Sat Feb 16 13:18:02 2008 +0900 +++ b/tools/Linda_library/Makefile Sun Dec 20 11:44:21 2009 +0900 @@ -1,7 +1,8 @@ CC=gcc AR=ar -CFLAGS=-c -g -Wall -FLAGS=-Wall -DDEBUG +CFLAGS=-g -O2 -Wall +#FLAGS=-Wall -DDEBUG +FLAGS=-Wall TARGET=ldserv liblindaapi.a LINDADIR=. LIBDIR=$(LINDADIR) @@ -11,9 +12,11 @@ ldserv : $(LINDADIR)/ldserv.c $(CC) $(FLAGS) -g -o ldserv $(LINDADIR)/ldserv.c -liblindaapi.a : $(LINDADIR)/lindaapi.c - $(CC) $(FLAGS) -g -c -o lindaapi.o $(LINDADIR)/lindaapi.c - $(AR) cr $(LIBDIR)/liblindaapi.a lindaapi.o +.c.o: + $(CC) $(CFLAGS) -c $^ -o $@ + +liblindaapi.a : lindaapi.o + $(AR) crus $@ $^ clean : rm -f $(TARGET) *.o diff -r 1bcc0070c2f6 -r 226c97efb693 tools/Linda_library/liblindaapi.a Binary file tools/Linda_library/liblindaapi.a has changed diff -r 1bcc0070c2f6 -r 226c97efb693 tools/Linda_library/lindaapi.c --- a/tools/Linda_library/lindaapi.c Sat Feb 16 13:18:02 2008 +0900 +++ b/tools/Linda_library/lindaapi.c Sun Dec 20 11:44:21 2009 +0900 @@ -2,7 +2,7 @@ // /*---------------------------------------------------------------------- - 󥯥롼ɥեɤ߹ + インクルードファイル読み込み ----------------------------------------------------------------------*/ #include #include @@ -11,13 +11,15 @@ #include #include #include -#include -#include #include #include #include #include +#include +#include +#include + #include "lindaapi.h" @@ -32,11 +34,11 @@ #endif /* Global Variables */ -static COMMAND *q_top, *q_end; /* ޥɥ塼 */ -static REPLY *reply, *r_end; /* ѥ塼 */ -static int qsize; /* ޥɥ塼Υ */ -static fd_set g_fds; /* ³Ƥ륿ץ륹ڡFD(FileDiscripter)ݻ */ -static unsigned int g_max_fds; /* ƻ뤹FDκ */ +static COMMAND *q_top, *q_end; /* コマンドキュー */ +static REPLY *reply, *r_end; /* 受け取り用キュー */ +static int qsize; /* コマンドキューのサイズ */ +static fd_set g_fds; /* 接続しているタプルスペース群のFD(FileDiscripter)を保持 */ +static unsigned int g_max_fds; /* 監視するFDの最大値 */ /* Static Functions */ static void unix_chkserv(int ps); @@ -53,10 +55,10 @@ /*-------------------------------------------------------------------/ static void count_packet (char type): - ѥåȤȤ + パケットの送受信カウントする - : - type - (char: s,r) + 引き数: + type - 送信、受信 (char型: s,r) /-------------------------------------------------------------------*/ static void count_packet(char type) @@ -95,20 +97,21 @@ #define unix_read_w read +#if 0 /*-------------------------------------------------------------------/ static int unix_write (int fd, unsigned char *buf, unsigned int size): - ФTUPLE롣 + サーバへTUPLEを送る。 - : - fd - ФΥեǥץ - buf - Фǡ(TUPLEإåޤ) - size - bufbyte - ֤: - ä(񤭤)ǡbyte + 引き数: + fd - サーバのファイルディスクリプタ + buf - サーバへ送るデータ(TUPLEヘッダ含む) + size - bufのbyte数 + 返り値: + 送った(書きこんだ)データのbyte数 /-------------------------------------------------------------------*/ static int -unix_write(int fd,unsigned char *buf,unsigned int size) { +unix_write_bak(int fd,unsigned char *buf,unsigned int size) { int i,nsize; nsize = htonl(size); i = write(fd,&nsize,INT_SIZE); @@ -118,6 +121,26 @@ #endif return(i); } +#endif + +static int +unix_write(int fd,unsigned char *buf,unsigned int size) { + int count=0; + uint32_t nsize; + + /* これから送信するデータのサイズをまず送信 */ + nsize = htonl(size); + write(fd, &nsize, INT_SIZE); + + /* 目的のデータを送信 */ + while (count < size) { + count += write(fd, buf+count, size-count); + } +#ifdef COUNT_PACKET + count_packet('s'); +#endif + return count+INT_SIZE; +} #define unix_write_w unix_write @@ -131,12 +154,12 @@ /*-------------------------------------------------------------------/ void init_linda(): - ѿνԤʤ + 大域変数の初期化等を行なう /-------------------------------------------------------------------*/ void init_linda() { FD_ZERO(&g_fds); - /* ѿϥꥢ + /* 大域変数はゼロクリアされる g_max_fds = 0; q_end = q_top = NULL; r_end = reply = NULL; @@ -148,15 +171,15 @@ /*-------------------------------------------------------------------/ int open_linda (char * hostname, int port): - LindaФȤΥͥΩץ륹ڡID֤ - ߤϥեǥץ֤Ƥ롣 + Lindaサーバとのコネクションを確立し、タプルスペースのIDを返す。 + 現在はファイルディスクリプタを返している。 - : - hostname - ФΥۥ̾ - port - ФΥݡֹ - ֤: - ͥΩȤΥեǥץ֤ - Ԥ -1 ֤ + 引き数: + hostname - サーバのホスト名 + port - サーバのポート番号 + 返り値: + コネクション確立が成功するとそのファイルディスクリプタを返す。 + 失敗すると -1 を返す。 /-------------------------------------------------------------------*/ int open_linda(char * hostname, int port){ @@ -168,16 +191,14 @@ if (hostname[0]=='/') { /* Unix domain */ if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == FAIL){ - fprintf(stderr, "socket open error! errno :%d %s\n", errno, - strerror(errno)); + perror("socket"); return(-1); } serv_addr_un.sun_family = AF_UNIX; strcpy(serv_addr_un.sun_path, hostname); fprintf(stdout,"connecting ... %d\n", serv_addr.sin_port); if (connect(fd, (struct sockaddr *)&serv_addr_un,sizeof(serv_addr_un)) == FAIL){ - fprintf(stderr,"connection error! errno :%d %s\n", errno, - strerror(errno)); + perror("connect"); close(fd); return(-1); } @@ -185,8 +206,7 @@ } else { /* INET domain */ if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == FAIL){ - fprintf(stderr, "socket open error! errno :%d %s\n", errno, - strerror(errno)); + perror("socket"); return(-1); } if ((hoste = gethostbyname(SERVER_NAME)) == NULL){ @@ -228,16 +248,14 @@ if (hostname[0]=='/') { /* Unix domain */ if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == FAIL){ - fprintf(stderr, "socket open error! errno :%d %s\n", errno, - strerror(errno)); + perror("socket"); return(-1); } serv_addr_un.sun_family = AF_UNIX; strcpy(serv_addr_un.sun_path, hostname); - fprintf(stdout,"connecting ... %d\n", serv_addr.sin_port); + DEB(fprintf(stdout,"connecting ... %d\n", serv_addr.sin_port)); if (connect(fd, (struct sockaddr *)&serv_addr_un,sizeof(serv_addr_un)) == FAIL){ - fprintf(stderr,"connection error! errno :%d %s\n", errno, - strerror(errno)); + perror("connect"); close(fd); return(-1); } @@ -245,8 +263,7 @@ } else { /* INET domain */ if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == FAIL){ - fprintf(stdout, "socket open error! errno :%d %s\n", errno, - strerror(errno)); + perror("socket"); return(-2); } serv_addr.sin_family = AF_INET; @@ -267,12 +284,11 @@ setsockopt (fd, IPPROTO_TCP, TCP_NODELAY, (char *) &tmp, sizeof (int)); } - fprintf(stdout,"connecting ... %d \n", ntohs(serv_addr.sin_port)); - fprintf(stdout," serv_addr.sin_port ... %d \n", ntohs(serv_addr.sin_port)); + DEB(fprintf(stdout,"connecting ... %d \n", ntohs(serv_addr.sin_port))); + DEB(fprintf(stdout," serv_addr.sin_port ... %d \n", ntohs(serv_addr.sin_port))); //fprintf(stdout," serv_addr.sin_addr.s_addr... %s\n", serv_addr.sin_addr.s_addr); if (connect(fd, (struct sockaddr *)&serv_addr,sizeof(serv_addr)) == FAIL){ - fprintf(stdout,"connection error! errno :%d %s\n", errno, - strerror(errno)); + perror("connect"); close(fd); return(-4); } @@ -281,7 +297,7 @@ FD_SET(fd, &g_fds); if (g_max_fds < fd) g_max_fds = fd; - fprintf(stdout," connect middle server %d\n", fd); + DEB(fprintf(stdout," connect middle server %d\n", fd)); return fd; } @@ -289,12 +305,12 @@ /*-------------------------------------------------------------------/ int close_linda(int tspace_id): - ³Ƥ륿ץ륹ڡؤ³ڤ롣 - åȤĤg_fds 鳰 - : - tspace_id - Ĥ륿ץ륹ڡID - ֤: - close + 接続しているタプルスペースへの接続を切る。 + ソケットを閉じ、g_fds から外す。 + 引数: + tspace_id - 閉じるタプルスペースのID + 返り値: + close の値 /-------------------------------------------------------------------*/ int close_linda(int tspace_id){ @@ -314,15 +330,15 @@ int psx_out (unsigned int tspace_id, unsigned int id, unsigned char *data, unsigned int size): - outޥɤCOMMAND塼ί롣 + outコマンドをCOMMANDキューへ溜める。 - : - tspace_id - ץ륹ڡID - id - ץID - data - ǡ - size - dataΥ - ֤: - ֹ + 引き数: + tspace_id - タプルスペースのID + id - タプルのID + data - 送信するデータ + size - dataのサイズ + 返り値: + シーケンス番号 /-------------------------------------------------------------------*/ int psx_out(unsigned int tspace_id, unsigned int id, @@ -340,18 +356,18 @@ int psx_ld (unsigned tspace_id, unsigned int id, char mode, void(*callback)(char*,void*), void * obj): - in,read,waitʤɤμޥɤCOMMAND塼ί롣 - psx_in,psx_rd,psx_wait_rdʤɤ֤Ƥ롣 + in,read,waitなどの受信コマンドをCOMMANDキューへ溜める。 + psx_in,psx_rd,psx_wait_rdなどに置き換えられている。 - : - tspace_id- ץ륹ڡID - id - ץID - mode - i,r,w ʸꡢơin,read,waitɽƤ롣 - callback - ХåѤδؿؤΥݥ󥿡 - ѤʤNULL򤤤롣 - obj - ХåѤؿΰ - ֤: - psx_queuemalloc줿REPLY¤ΤؤΥݥ + 引き数: + tspace_id- タプルスペースのID + id - タプルのID + mode - i,r,w の文字を取り、各々in,read,waitを表している。 + callback - コールバックを使用する場合の関数へのポインタ。 + 使用しない場合はNULLをいれる。 + obj - コールバックで用いる関数の引き数。 + 返り値: + psx_queue内でmallocされたREPLY構造体へのポインタ /-------------------------------------------------------------------*/ int psx_ld(unsigned int tspace_id, unsigned int id, @@ -366,13 +382,13 @@ /*-------------------------------------------------------------------/ unsigned char * psx_reply (int seq): - Ф褿ǡ֤ + サーバから答えが来たデータを返す。 - : - seq - psx_ld()֤͡ - ֤: - seqбǡ֤ǡޤƤʤ - NULL֤ + 引き数: + seq - psx_ld()が返した値。 + 返り値: + seqに対応したデータを返す。データをまだ受信していない場合は + NULLを返す。 /-------------------------------------------------------------------*/ unsigned char * psx_reply(int seq){ @@ -420,8 +436,8 @@ /*-------------------------------------------------------------------/ void psx_sync_n (): - Фȥǡ򤹤롣COMMAND塼ίޤäǡ - Ф褿ǡбREPLYؤ롣 + サーバとデータの送受信をする。COMMANDキューに溜まったデータを + 送信し、サーバから送られて来たデータを対応するREPLYへいれる。 /-------------------------------------------------------------------*/ #define TIMEDELTA 10 void @@ -461,23 +477,23 @@ psx_queue (unsigned int tspace_id, unsigned int id, unsigned int size, unsigned char *data, char mode, void(*callback)(char*,void*), void * obj): - out,in,read,waitʤɤΥޥɤCOMMAND塼ί롣ǡ - 륳ޥ(in,read,wait)ΤȤϼäȤ˥ǡ - ǼREPLY¤Τ롣 + out,in,read,waitなどのコマンドをCOMMANDキューに溜める。データを + 受信するコマンド(in,read,wait)のときは受け取ったときにデータを + 格納するREPLY構造体を作る。 - : - tspace_id- 西ץ륹ڡID - id - TUPLE SpaceID - size - dataΥ - data - ǡNULL - mode - ޥɤΥ⡼(out,in,read,wait ϳơchar: o,i,r,w) - callback - ХåѤδؿؤΥݥ󥿡 - ѤʤNULL - obj - ХåѤؿ˰Ϥǡ - ֤: - - mallocREPLY¤ΤؤΥݥ󥿡outξ - 0֤롣 - Ԥ - FAIL(-1)֤롣 + 引き数: + tspace_id- 送信先タプルスペースのID + id - アクセスするTUPLE SpaceのID + size - dataのサイズ + data - 送信するデータ。受信時はNULL。 + mode - コマンドのモード(out,in,read,wait は各々char型: o,i,r,w) + callback - コールバックを使用する場合の関数へのポインタ。 + 使用しない場合はNULL。 + obj - コールバックで用いる関数に引き渡すデータ。 + 返り値: + 成功した場合 - mallocしたREPLY構造体へのポインタ。outの場合は + 0が返る。 + 失敗した場合 - FAIL(-1)が返る。 /-------------------------------------------------------------------*/ static int psx_queue(unsigned int tspace_id, unsigned int id, @@ -504,14 +520,14 @@ q_end = q_end->next; } - /* size DATASIZE */ + /* size は DATASIZE */ if ((q_end->command = (unsigned char *) malloc(size+LINDA_HEADER_SIZE)) == NULL) { psx_free(q_end); c->next = NULL; return(FAIL); } - /* ǡ׵(in,rd,wait)ʤѤȢѰ */ + /* データ受け取り要求(in,rd,wait)なら受け取り用の箱を用意 */ if (mode != 'o') { if (reply == NULL){ if ((reply = (REPLY *) malloc (sizeof(REPLY))) == NULL){ @@ -525,7 +541,7 @@ p = r_end->next; r_end = p; p->next = NULL; } p->mode = '?'; - p->seq = (int)p; // ¤ΤΥɥ쥹Ǽ + p->seq = (int)p; // 構造体のアドレスで識別 p->callback = callback; p->obj = obj; PSX_Debug(("psx_queue: seq %d reply %x p %x r_end %x",seq,reply,p,r_end)); @@ -559,12 +575,12 @@ /*-------------------------------------------------------------------/ static void unix_chkserv (int ps): - Фǡ(TUPLE)롣REPLY¤Τ˥Хåؿ - ꤵƤФδؿ¹ԤREPLY¤Τ򥭥塼 - ХåؿꤵƤʤREPLY¤Τ˥ǡ - Ϥ - : - ps - ³Ƥ륿ץ륹ڡΥå + サーバからデータ(TUPLE)を受け取る。REPLY構造体にコールバック関数 + が指定されていればその関数を実行し、REPLY構造体をキューから取り + 除く。コールバック関数が指定されていなければREPLY構造体にデータ + を引き渡す。 + 引数: + ps - 接続しているタプルスペースのソケット /-------------------------------------------------------------------*/ static void unix_chkserv(int ps){ @@ -574,15 +590,14 @@ unsigned char * tuple = 0; if((i=read(ps,&npkt,INT_SIZE))<0) { - fprintf(stderr, "size read error! on fd:%d %s\n", ps, - strerror(errno)); + perror("read"); exit(1); } pkt = ntohl(npkt); DEB(printf("pkt: %d\n",pkt)); DEB(fprintf(stdout, "psx_chkserv: queue number: %d , size = %d\n", i, pkt)); if((tuple = (unsigned char *)malloc(pkt))==NULL){ - fprintf(stderr,"allocate error! errno :%d %s",errno,strerror(errno)); + perror("malloc"); exit(1); } for(a=0;a ' % sys.argv[0] + sys.exit(1) + + main(int(sys.argv[1]), int(sys.argv[2])) diff -r 1bcc0070c2f6 -r 226c97efb693 tools/StopProcess.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/StopProcess.py Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,46 @@ +#! /usr/bin/env python +"""find and kill processes +""" +import pexpect +import re +import sys +import os + +def main(proc): + child = pexpect.spawn('ps aucxwww') + child.setwinsize(100,300) + child.expect(pexpect.EOF) + + pslist = child.before.splitlines() + # separate string by space + fmt = re.split(' +', pslist[0]) + + if fmt[-1] == '': + fmt.pop() + if fmt[0] == '': + fmt.pop(0) + lenfmt = len(fmt) + + # indexing, key is format of output of ps command, value is number of list + index = dict([(k,v) for (k,v) in zip(fmt, range(0,lenfmt))]) + + # find ".*.*" in 'COMMAND' part + pars = re.compile(".*"+proc+".*") + + for l in pslist[1:]: + elm = re.split(' +',l ,lenfmt) + cmd = elm[index['COMMAND']] + result = pars.match(cmd) + + if (result is not None): + os.system('kill -KILL ' + elm[index['PID']]) + print 'stop', elm[index['PID']], ':', cmd + + +if __name__== "__main__": + if (len(sys.argv) != 2): + print "Usage : %s " % sys.argv[0] + sys.exit(1) + + main(sys.argv[1]) + diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/.project --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/.project Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,11 @@ + + + java3d-test + + + + + + + + diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/.settings/org.eclipse.core.resources.prefs --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/.settings/org.eclipse.core.resources.prefs Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,3 @@ +#Mon Aug 25 16:36:05 JST 2008 +eclipse.preferences.version=1 +encoding//src/HelloWorld.xml=UTF-8 diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/HashMapSample.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/HashMapSample.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,29 @@ +import java.util.Map; +import java.util.HashMap; + +public class HashMapSample { + public void get(Map map){ + for (String str : map.keySet()){ + System.out.println(str + ": " + map.get(str)); + } + } + + public static void main(String[] args){ + //HashMapのインスタンス化 + Map map = new HashMap(); + + String[] keyword = {"Bounds", "Stroke"}; + String[] possition = {"210, 100", "100, 100"}; + System.out.println("HashTest > "); + + //HashMapのput + for (int i = 0; i < keyword.length; i++){ + map.put(keyword[i], possition[i]); + } + HashMapSample getSample = new HashMapSample(); + getSample.get(map); + + + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/HelloUniverse.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/HelloUniverse.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,134 @@ +/* + * @(#)HelloUniverse.java 1.55 02/10/21 13:43:36 + * + * Copyright (c) 1996-2002 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any + * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND + * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY + * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES + * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR + * DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN + * OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR + * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR + * PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF + * LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, + * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that Software is not designed,licensed or intended + * for use in the design, construction, operation or maintenance of + * any nuclear facility. + */ + +import java.applet.Applet; +import java.awt.BorderLayout; +import java.awt.event.*; +import java.awt.GraphicsConfiguration; +import com.sun.j3d.utils.applet.MainFrame; +import com.sun.j3d.utils.geometry.ColorCube; +import com.sun.j3d.utils.universe.*; +import javax.media.j3d.*; +import javax.vecmath.*; + +public class HelloUniverse extends Applet { + + private SimpleUniverse u = null; + + public BranchGroup createSceneGraph() { + // Create the root of the branch graph + BranchGroup objRoot = new BranchGroup(); + + RotationInterpolator rotator = addCube(objRoot, new Point3d(0.0,0.0,0.0), new Alpha(-1, 4000)); + objRoot.addChild(rotator); + RotationInterpolator rotator1 = addCube(objRoot, new Point3d(1.0,0.0,0.0), new Alpha(4000, -1)); + objRoot.addChild(rotator1); + + // Have Java 3D perform optimizations on this scene graph. + objRoot.compile(); + + return objRoot; + } + + private RotationInterpolator addCube(BranchGroup objRoot, Point3d position, Alpha alpha) { + // Create the TransformGroup node and initialize it to the + // identity. Enable the TRANSFORM_WRITE capability so that + // our behavior code can modify it at run time. Add it to + // the root of the subgraph. + TransformGroup objTrans = new TransformGroup(); + objTrans.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); + objRoot.addChild(objTrans); + + // Create a simple Shape3D node; add it to the scene graph. + objTrans.addChild(new ColorCube(0.4)); + + // Create a new Behavior object that will perform the + // desired operation on the specified transform and add + // it into the scene graph. + Transform3D yAxis = new Transform3D(); + TransformGroup transRoot = new TransformGroup(); + Transform3D transform = new Transform3D(); + Alpha rotationAlpha = alpha; + + transform.set(new Vector3d(1.0, 1.0, 1.0)); + transRoot.setTransform(transform); + + RotationInterpolator rotator = + new RotationInterpolator(rotationAlpha, objTrans, yAxis, + 0.0f, (float) Math.PI*2.0f); + BoundingSphere bounds = + new BoundingSphere(position, 100.0); + rotator.setSchedulingBounds(bounds); + return rotator; + } + + public HelloUniverse() { + } + + public void init() { + setLayout(new BorderLayout()); + GraphicsConfiguration config = + SimpleUniverse.getPreferredConfiguration(); + + Canvas3D c = new Canvas3D(config); + add("Center", c); + + // Create a simple scene and attach it to the virtual universe + BranchGroup scene = createSceneGraph(); + u = new SimpleUniverse(c); + + // This will move the ViewPlatform back a bit so the + // objects in the scene can be viewed. + u.getViewingPlatform().setNominalViewingTransform(); + + u.addBranchGraph(scene); + } + + public void destroy() { + u.cleanup(); + } + + // + // The following allows HelloUniverse to be run as an application + // as well as an applet + // + public static void main(String[] args) { + new MainFrame(new HelloUniverse(), 256, 256); + } +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/HelloWorld.xml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/HelloWorld.xml Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,2 @@ + +<アラン 演技力="10" 歌唱力="8" スター性="2" 勘違い="10" 特殊能力="10"> \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/HelloWorldSax.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/HelloWorldSax.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,59 @@ +import javax.xml.parsers.*; +import org.xml.sax.*; +import org.xml.sax.helpers.*; +import java.io.*; + +public class HelloWorldSax extends DefaultHandler { + public static void main(String[] argv) { + try { + // SAXパーサーファクトリを生成 + SAXParserFactory spfactory = SAXParserFactory.newInstance(); + // SAXパーサーを生成 + SAXParser parser = spfactory.newSAXParser(); + // XMLファイルを指定されたデフォルトハンドラーで処理 + parser.parse(new File("src/example.graffle"), new HelloWorldSax()); + } catch (Exception e) { + e.printStackTrace(); + } + } + /** + * ドキュメント開始時 + */ + public void startDocument() { + System.out.println("ドキュメント開始"); + } + /** + * 要素の開始タグ読み込み時 + */ + public void startElement(String uri, + String localName, + String qName, + Attributes attributes) { + + System.out.println("要素開始:" + qName); + } + /** + * テキストデータ読み込み時 + */ + public void characters(char[] ch, + int offset, + int length) { + + System.out.println("テキストデータ:" + new String(ch, offset, length)); + } + /** + * 要素の終了タグ読み込み時 + */ + public void endElement(String uri, + String localName, + String qName) { + + System.out.println("要素終了:" + qName); + } + /** + * ドキュメント終了時 + */ + public void endDocument() { + System.out.println("ドキュメント終了"); + } +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/Java2dTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/Java2dTest.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,72 @@ +import java.awt.*; +import java.awt.geom.*; +import java.awt.event.*; +import javax.swing.*; +import java.awt.image.BufferedImage; +import java.io.File; +import javax.imageio.ImageIO; +import java.io.IOException; + +public class Java2dTest extends JFrame{ + + public static void main(String[] args){ + Java2dTest test = new Java2dTest(); + + test.addWindowListener(new WindowAdapter(){ + public void windowClosing(WindowEvent e){System.exit(0);} + }); + + test.setBounds( 0, 0, 200, 200); + test.setVisible(true); + } + + public void paint(Graphics g){ + Graphics2D g2 = (Graphics2D)g; + + BufferedImage readImage = null; + try { + readImage = ImageIO.read(new File("sample.png")); + } catch (Exception e) { + e.printStackTrace(); + readImage = null; + } + + if (readImage == null){ + readImage = new BufferedImage(getWidth(), getHeight(), + BufferedImage.TYPE_INT_BGR); + } + + Graphics2D off = readImage.createGraphics(); + + off.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + BasicStroke wideStroke = new BasicStroke(4.0f); + off.setStroke(wideStroke); + + off.setPaint(Color.white); + off.draw(new Ellipse2D.Double(30, 40, 50, 50)); + + off.setPaint(Color.blue); + off.draw(new Ellipse2D.Double(70, 40, 50, 50)); + + off.setPaint(Color.red); + off.draw(new Ellipse2D.Double(110, 40, 50, 50)); + + off.setPaint(Color.yellow); + off.fill(new Arc2D.Double(50, 100, 110, 110, 330, 100, Arc2D.PIE)); + off.setPaint(Color.gray); + off.draw(new Arc2D.Double(50, 100, 110, 110, 330, 100, Arc2D.PIE)); + + if (readImage != null){ + g2.drawImage(readImage, 0, 0, this); + } + + try { + boolean result = + ImageIO.write(readImage, "png", new File("sample2.png")); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/Java3DProgram.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/Java3DProgram.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,77 @@ +// Java3DProgram.java + +import java.applet.Applet; +import com.sun.j3d.utils.applet.MainFrame; +import javax.media.j3d.*; +import javax.vecmath.*; +import java.awt.*; + +import com.sun.j3d.utils.universe.*; +import com.sun.j3d.utils.geometry.ColorCube; +import com.sun.j3d.utils.behaviors.vp.OrbitBehavior; + +/* + + +*/ + +public class Java3DProgram extends Applet { + + public SimpleUniverse universe = null; + public Canvas3D canvas = null; + + public BranchGroup createObjects() { + + BranchGroup root = new BranchGroup(); + + // 平行移動を定義 + TransformGroup transRoot = new TransformGroup(); + Transform3D transform = new Transform3D(); + + // x方向に1.0m移動 + transform.set(new Vector3d(1.0, 0, 0)); + transRoot.setTransform(transform); + + // 色つき立方体の作成 + transRoot.addChild(new ColorCube(0.4)); + root.addChild(transRoot); + root.compile(); + + return root; + } + + public void setOrbitBehavior() { + + // マウスでぐりぐりするための処理 + OrbitBehavior orbit = new OrbitBehavior(canvas, OrbitBehavior.REVERSE_ALL); + orbit.setSchedulingBounds( + new BoundingSphere(new Point3d(0, 0, 0), 100.0)); + universe.getViewingPlatform().setViewPlatformBehavior(orbit); + } + + public void init() { + + setLayout(new BorderLayout()); + + // キャンバスの作成 + GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); + Canvas3D canvas = new Canvas3D(config); + add("Center", canvas); + + // SimpleUniverse の作成 + universe = new SimpleUniverse(canvas); + + // カメラの移動(原点から少しだけ後ろにずれる) + universe.getViewingPlatform().setNominalViewingTransform(); + + // マウスでぐりぐり動かすための処理 + setOrbitBehavior(); + + // オブジェクトの追加 + universe.addBranchGraph(createObjects()); + } + + public static void main(String[] args) { + new MainFrame(new Java3DProgram(), 200, 200); + } +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/OmnigraffleNode.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/OmnigraffleNode.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,20 @@ +import java.util.*; + +//dictでオムニグラフのノードオブジェクトを作成 +//keyが来る、keyの中にはdict or element +//既にノードがあったらkeyの値をstringで取っておく +//次に来た時にstingかintegerの時はkeyの値が入っていたらkeyとの型のペアのオブジェクトを作成 +//charsが来たらkeyとの型のノードに代入する。 +// /dictが来たらkeyはnullに戻す。endelement、tempで作ったノードはnullにする +//key int はテンポラリで作ったノードに代入 +//elementに来たら実行 + +public class OmnigraffleNode { +// String[] keyword = {"Bounds", "Points"}; + HashMap map = new HashMap(); + + public void addinteger(String name, String i){ + map.put(name, i); + } + +} diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/Sample3D.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/Sample3D.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,73 @@ +import javax.swing.*; +import java.awt.event.*; +import java.awt.BorderLayout; +import java.awt.GraphicsConfiguration; +import com.sun.j3d.utils.universe.*; +import javax.media.j3d.*; +//import javax.vecmath.*; +import com.sun.j3d.utils.geometry.ColorCube; +import com.sun.j3d.utils.behaviors.mouse.MouseRotate; +import com.sun.j3d.utils.behaviors.mouse.MouseTranslate; +import com.sun.j3d.utils.behaviors.mouse.MouseZoom; + +public class Sample3D extends JFrame { + public BranchGroup createSceneGraph() { + BranchGroup objRoot = new BranchGroup(); + + TransformGroup objTrans = new TransformGroup(); + objRoot.addChild(objTrans); + + objTrans.setCapability( TransformGroup.ALLOW_TRANSFORM_READ ); + objTrans.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE ); + + MouseRotate rotat = new MouseRotate( objTrans ); + MouseTranslate trans = new MouseTranslate( objTrans ); + MouseZoom zoom = new MouseZoom( objTrans ); + + BoundingSphere bounds = new BoundingSphere(); + bounds.setRadius( 10.0 ); + rotat.setSchedulingBounds( bounds ); + trans.setSchedulingBounds( bounds ); + zoom.setSchedulingBounds( bounds ); + + objTrans.addChild(rotat); + objTrans.addChild(trans); + objTrans.addChild(zoom); + + ColorCube colorCube = new ColorCube(0.5d); + + objTrans.addChild(colorCube); + objRoot.compile(); + return objRoot; + } + + public Sample3D() { + getContentPane().setLayout(new BorderLayout()); + + GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); + + Canvas3D canvas = new Canvas3D(config); + getContentPane().add("Center", canvas); + + BranchGroup scene = createSceneGraph(); + SimpleUniverse universe = new SimpleUniverse(canvas); + + universe.getViewingPlatform().setNominalViewingTransform(); + + universe.addBranchGraph(scene); + } + public static void main(String[] args) { + Sample3D sample = new Sample3D(); + + /* サイズ指定 */ + sample.setBounds( 10, 10, 240, 240); + + /* 終了処理を追加 */ + sample.addWindowListener(new WindowAdapter(){ + public void windowClosing(WindowEvent e){System.exit(0);} + }); + /* 実際に表示する */ + sample.setVisible(true); + } +} + diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/Sample3D6.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/Sample3D6.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,72 @@ +import javax.swing.*; +import java.awt.event.*; +import java.awt.BorderLayout; +import java.awt.GraphicsConfiguration; +import com.sun.j3d.utils.universe.*; +import javax.media.j3d.*; +import com.sun.j3d.utils.geometry.Box; +import javax.vecmath.*; + +public class Sample3D6 extends JFrame { + public BranchGroup createSceneGraph() { + BranchGroup objRoot = new BranchGroup(); + + objRoot.addChild(createLight()); + + Appearance ap = new Appearance(); + Material ma = new Material(); + ma.setDiffuseColor(0.0f, 0.0f, 1.0f); + ap.setMaterial(ma); + + Box box = new Box( 0.2f, 0.5f, 0.3f, ap); + + Transform3D t3dy = new Transform3D(); + t3dy.rotY(Math.PI / 6); + Transform3D t3dx = new Transform3D(); + t3dx.rotX(Math.PI / 4); + + Transform3D t3d = new Transform3D(); + t3d.mul(t3dy, t3dx); + + TransformGroup objTrans = new TransformGroup(t3d); + objRoot.addChild(objTrans); + + objTrans.addChild(box); + objRoot.compile(); + + return objRoot; + } + + private Light createLight(){ + DirectionalLight light = new DirectionalLight( true, + new Color3f(0.0f, 0.0f, 1.0f), + new Vector3f(0.0f, 0.0f, -1.0f)); + + light.setInfluencingBounds(new BoundingSphere(new Point3d(), 100.0)); + + return light; + } + + public Sample3D6() { + getContentPane().setLayout(new BorderLayout()); + + GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); + + Canvas3D canvas = new Canvas3D(config); + getContentPane().add(canvas, BorderLayout.CENTER); + + BranchGroup scene = createSceneGraph(); + SimpleUniverse universe = new SimpleUniverse(canvas); + + universe.getViewingPlatform().setNominalViewingTransform(); + universe.addBranchGraph(scene); + } + + public static void main(String[] args) { + Sample3D6 sample = new Sample3D6(); + + sample.setBounds( 10, 10, 240, 240); + sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + sample.setVisible(true); + } +} diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/SampleHandler.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/SampleHandler.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,97 @@ +import org.xml.sax.*; +import org.xml.sax.helpers.*; + +class SampleHandler extends DefaultHandler{ + private int tab=0; + private String currentTag; + + /* XML文書の開始時の処理*/ + public void startDocument(){ + System.out.println("Here is start of XML document."); + } + + /* 要素の開始時の処理*/ + public void startElement(String namespaceURI,String localName,String qName,Attributes attrs){ + tabbing(); + System.out.println("Start Element"); + /* namespaceURIの表示 要調査*/ + if(namespaceURI!=""){ + tabbing(); + System.out.println("namespaceURI= "+namespaceURI); + } + /* localNameの表示 要調査*/ + if(localName!=""){ + tabbing(); + System.out.println("localName= "+localName); + } + /*タグ名を表示*/ + if(qName != ""){ + tabbing(); + System.out.println("qName= "+qName); + currentTag=qName; + } + /* 属性の表示*/ + /* 属性の数はAttributesのgetLength()で取得*/ + if(attrs.getLength()!=0){ + tabbing(); + /* 属性の値はAttributesのgetValue(int)で取得*/ + System.out.println("attrs= "+attrs.getValue(0)); + } + tab++; + } + + /*要素の終了時の処理*/ + public void endElement(String namespaceURI,String localName,String qName){ + tab--; + tabbing(); + System.out.println("End element."); + if(namespaceURI!=""){ + tabbing(); + System.out.println("namespaceURI= "+namespaceURI); + } + if(localName!=""){ + tabbing(); + System.out.println("localName= "+localName); + } + + if(qName!=""){ + tabbing(); + System.out.println("qName= "+qName); + } + currentTag=""; + } + + /* XML文書の終了時の処理*/ + public void endDocument(){ + System.out.println("Here is end of XML document."); + } + + /* 文字列の処理*/ + public void characters(char[] ch,int start,int length){ + if(currentTag.equals("key")){ + String str=new String(ch,start,length); + if(str.length()!=0){ + tab++; + tabbing(); + tab--; + System.out.println("====="+str+"====="); + } + } + } + + /* 処理命令を受けた時の処理 要調査*/ + public void processingInstruction(String target,String data){} + + /* プレフィックスによる名前空間の範囲の開始時 要調査*/ + public void startPrefixMapping(String prefix,String uri){} + + /* プレフィックスによる名前空間の範囲の終了時 要調査*/ + public void endPrefixMapping(String prefix){} + + /* インデント用.これはこのクラス独自のメソッド*/ + private void tabbing(){ + for(int i=0;i + + + アラン + four + 8 + 2 + 10 + 10 + + diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/example.graffle --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/example.graffle Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,380 @@ + + + + + ActiveLayerIndex + 0 + AutoAdjust + + CanvasColor + + w + 1 + + CanvasOrigin + {0, 0} + CanvasScale + 1 + ColumnAlign + 1 + ColumnSpacing + 36 + CreationDate + 2006-02-14 12:48:50 +0900 + Creator + 安村恭一 + DisplayScale + 1 cm = 1 cm + GraphDocumentVersion + 5 + GraphicsList + + + Class + LineGraphic + Head + + ID + 11 + + ID + 25 + Points + + {299, 125.5} + {299, 205.5} + + Style + + stroke + + HeadArrow + 0 + TailArrow + 0 + + + Tail + + ID + 9 + + + + Class + LineGraphic + Head + + ID + 10 + + ID + 24 + Points + + {277.767, 115.479} + {156.233, 215.521} + + Style + + stroke + + HeadArrow + 0 + TailArrow + 0 + + + Tail + + ID + 9 + + + + Class + LineGraphic + Head + + ID + 9 + + ID + 23 + Points + + {162.5, 98} + {271.5, 98} + + Style + + stroke + + HeadArrow + 0 + TailArrow + 0 + + + Tail + + ID + 2 + + + + Bounds + {{272, 206}, {54, 54}} + Class + ShapedGraphic + ID + 11 + Shape + Circle + + + Bounds + {{108, 206}, {54, 54}} + Class + ShapedGraphic + ID + 10 + Shape + Circle + + + Bounds + {{272, 71}, {54, 54}} + Class + ShapedGraphic + ID + 9 + Shape + Circle + + + Bounds + {{108, 71}, {54, 54}} + Class + ShapedGraphic + ID + 2 + Shape + Circle + + + GridInfo + + GridSpacing + 14.17322826385498 + MajorGridSpacing + 10 + + GuidesLocked + NO + GuidesVisible + YES + HPages + 1 + ImageCounter + 1 + IsPalette + NO + KeepToScale + + Layers + + + Lock + NO + Name + Layer 1 + Print + YES + View + YES + + + LayoutInfo + + ChildOrdering + 0 + + LinksVisible + NO + MagnetsVisible + NO + MasterSheet + マスター 1 + MasterSheets + + + ActiveLayerIndex + 0 + AutoAdjust + + CanvasColor + + w + 1 + + CanvasOrigin + {0, 0} + CanvasScale + 1 + ColumnAlign + 1 + ColumnSpacing + 36 + DisplayScale + 1 cm = 1 cm + GraphicsList + + GridInfo + + GridSpacing + 14.17322826385498 + MajorGridSpacing + 10 + + HPages + 1 + IsPalette + NO + KeepToScale + + Layers + + + Lock + NO + Name + レイヤー 1 + Print + YES + View + YES + + + LayoutInfo + + ChildOrdering + 0 + + Orientation + 2 + RowAlign + 1 + RowSpacing + 36 + SheetTitle + マスター 1 + UniqueID + 1 + VPages + 1 + + + ModificationDate + 2008-02-07 22:06:25 +0900 + Modifier + Fuchita Yoshihiko + NotesVisible + NO + Orientation + 2 + OriginVisible + NO + PageBreaks + YES + PrintInfo + + NSBottomMargin + + float + 0 + + NSJobFeatures + + coded + BAt0eXBlZHN0cmVhbYED6IQBQISEhBNOU011dGFibGVEaWN0aW9uYXJ5AISEDE5TRGljdGlvbmFyeQCEhAhOU09iamVjdACFhAFpAIY= + + NSLeftMargin + + float + 0 + + NSPagesPerSheet + + int + 1 + + NSPaperSize + + size + {595, 842} + + NSPrintAllPages + + int + 0 + + NSReversePageOrder + + int + 0 + + NSRightMargin + + float + 0 + + NSTopMargin + + float + 0 + + + ReadOnly + NO + RowAlign + 1 + RowSpacing + 36 + SheetTitle + Canvas 1 + SmartAlignmentGuidesActive + YES + SmartDistanceGuidesActive + YES + UniqueID + 1 + UseEntirePage + + VPages + 1 + WindowInfo + + CurrentSheet + 0 + DrawerOpen + + DrawerTab + Outline + DrawerWidth + 209 + FitInWindow + + Frame + {{324, 0}, {574, 800}} + ShowRuler + + ShowStatusBar + + VisibleRegion + {{0, 0}, {559, 686}} + Zoom + 1 + + + diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/graff3d.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/graff3d.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,529 @@ +// Draw the graph of a function +// version 1.0 (c) K.Sasano + +import java.applet.Applet; +import java.awt.*; +import java.awt.event.*; +import java.awt.BorderLayout; +import java.awt.Frame; +import java.awt.Font; +import java.awt.GraphicsConfiguration; +import java.util.Enumeration; +import javax.media.j3d.*; +import javax.vecmath.*; +import com.sun.j3d.utils.universe.*; +import com.sun.j3d.utils.applet.MainFrame; +import com.sun.j3d.utils.behaviors.mouse.MouseRotate; +import com.sun.j3d.utils.behaviors.mouse.MouseTranslate; +import com.sun.j3d.utils.behaviors.mouse.MouseZoom; +import com.sun.j3d.utils.geometry.Text2D; + +public class graff3d extends Applet { + + // global variables + float xwidth; + float x0; + float ywidth; + float y0; + float xdelta; + float ydelta; + float z0; + float zwidth; + float zvalue[][]; + float zcenter[][]; + Shape3D surfaceGraph; + Shape3D meshGraph; + Shape3D xyPlane; + Shape3D xyzAxes; + Shape3D xyzArrowHead; + TransformGroup xyzAxesLabels; + + //key behavior + public class KeyBehavior extends Behavior{ + + private BranchGroup bg; + private WakeupOnAWTEvent wue; + + KeyBehavior(BranchGroup bg){ + this.bg=bg; + } + + public void initialize(){ + this.wakeupOn(wue = new WakeupOnAWTEvent(KeyEvent.KEY_PRESSED)); + } + + public void processStimulus(Enumeration criteria){ + AWTEvent ae = (wue.getAWTEvent())[0]; + char c=((KeyEvent)ae).getKeyChar(); + TransparencyAttributes + surftr = (surfaceGraph.getAppearance()).getTransparencyAttributes(); + TransparencyAttributes + meshtr = (meshGraph.getAppearance()).getTransparencyAttributes(); + TransparencyAttributes + xytr = (xyPlane.getAppearance()).getTransparencyAttributes(); + + if(c=='s'){ //Show/Erase surfacegraph + addSurface=!addSurface; + if(addSurface){ + surftr = new TransparencyAttributes(TransparencyAttributes.NONE,0.0f); + }else{ + surftr = new TransparencyAttributes(TransparencyAttributes.NICEST,1.0f); + } + } + if(c=='m'){ //Show/Erase meshgraph + float tr; + addMesh=!addMesh; + if(addMesh){ tr= 0.0f; } else { tr=1.0f; } + meshtr = new TransparencyAttributes(TransparencyAttributes.NICEST,tr); + } + if(c=='z'){ //Show/Erase xyplane + float tr; + addXYPlane=!addXYPlane; + if(addXYPlane){ tr= 0.6f; } else { tr=1.0f; } + xytr = new TransparencyAttributes(TransparencyAttributes.NICEST,tr); + } + (xyPlane.getAppearance()).setTransparencyAttributes(xytr); + (meshGraph.getAppearance()).setTransparencyAttributes(meshtr); + (surfaceGraph.getAppearance()).setTransparencyAttributes(surftr); + + this.wakeupOn(wue = new WakeupOnAWTEvent(KeyEvent.KEY_PRESSED)); + } + } + + //create scene + public BranchGroup createSceneGraph() { + BranchGroup objRoot = new BranchGroup(); + BoundingSphere bounds = new BoundingSphere(); + bounds.setRadius( 1000.0 ); + + //prepare for movement + TransformGroup objTrans = new TransformGroup(); + objRoot.addChild(objTrans); + + objTrans.setCapability( TransformGroup.ALLOW_TRANSFORM_READ ); + objTrans.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE ); + + MouseRotate rotat = new MouseRotate( objTrans ); + MouseTranslate trans = new MouseTranslate( objTrans ); + MouseZoom zoom = new MouseZoom( objTrans ); + + rotat.setSchedulingBounds( bounds ); + trans.setSchedulingBounds( bounds ); + zoom.setSchedulingBounds( bounds ); + + objTrans.addChild(rotat); + objTrans.addChild(trans); + objTrans.addChild(zoom); + + //add xy-plane + objTrans.addChild(xyPlane); + + //add graphs + objTrans.addChild(surfaceGraph); + objTrans.addChild(meshGraph); + + //add axes + objTrans.addChild(xyzAxes); //axis + objTrans.addChild(xyzArrowHead); //arrowhead + objTrans.addChild(xyzAxesLabels); //label + + //add key behavior + KeyBehavior myKeyBehav=new KeyBehavior(objRoot); + myKeyBehav.setSchedulingBounds( bounds ); + objRoot.addChild(myKeyBehav); + + //compile the object + objRoot.compile(); + + return objRoot; + } + + //surface graph + private Shape3D graph(){ + int totalN=6*n*n; + + Point3f coord[] = new Point3f[totalN]; + Color3f color[] = new Color3f[totalN]; + + for(int i=0; i1){ r=1.0f; g=0.5f; b=0.0f; } + else if(h>0){ r=h*1.0f; g=0.75f-h*0.25f; b=0.0f; } + else if(h>-1){ r=0.0f; g=(1+h)*0.75f; b= -h*0.75f; } + else{ r=0.0f; g=0.0f; b=0.75f;} + return new Color3f(r,g,b); + } + + //mesh graph + private Shape3D meshgraph(){ + //construct coordinat data + int totalN=2*(nmesh+1)*(nmesh+1); + + Point3f coord[] = new Point3f[totalN]; + Color3f color[] = new Color3f[totalN]; + Color3f lcolor = new Color3f(1.0f, 1.0f, 1.0f); + + for(int i=0; i<=nmesh; i++){ + float xi=xmin+i*(xmax-xmin)/nmesh; + + for(int j=0; j<=nmesh; j++){ + int tmp=i*(nmesh+1)+j; + int tmp1=j*(nmesh+1)+i+(nmesh+1)*(nmesh+1); + float yj=ymin+j*(ymax-ymin)/nmesh; + + coord[tmp]=new Point3f(xn(xi),yn(yj),zn(f(xi,yj))); + color[tmp]=lcolor; + + coord[tmp1]=coord[tmp]; + color[tmp1]=color[tmp]; + } + } + + int stripCounts[]; + stripCounts= new int[2*(nmesh+1)]; + for(int i=0; i<=2*nmesh+1; i++){stripCounts[i]=nmesh+1;} + + LineStripArray lsa = + new LineStripArray( + totalN, + LineStripArray.COORDINATES|LineStripArray.COLOR_3, + stripCounts + ); + lsa.setCoordinates(0,coord); + lsa.setColors(0,color); + + //construct appearence + LineAttributes attr = new LineAttributes(); + attr.setLineWidth(meshLineWidth); + + float tr; + if(addMesh){ tr= 0.0f; } else { tr=1.0f; } + TransparencyAttributes transAttrib; + transAttrib = new TransparencyAttributes(TransparencyAttributes.NICEST,tr); + + Appearance appear = new Appearance(); + appear.setLineAttributes(attr); + appear.setTransparencyAttributes(transAttrib); + appear.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_READ); + appear.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_WRITE); + + //construct Shape3D for meshgraph + Shape3D graphshape=new Shape3D(); + graphshape.removeGeometry(0); + graphshape.addGeometry(lsa); + graphshape.setAppearance(appear); + graphshape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + graphshape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + + return graphshape; + } + + //xy-plane + private Shape3D xyplane(){ + QuadArray xyp= new QuadArray(4,QuadArray.COORDINATES|QuadArray.COLOR_3); + xyp.setCoordinate(0,new Point3f(0.5f,0.5f,zn(0.0f))); + xyp.setCoordinate(1,new Point3f(-0.5f,0.5f,zn(0.0f))); + xyp.setCoordinate(2,new Point3f(-0.5f,-0.5f,zn(0.0f))); + xyp.setCoordinate(3,new Point3f(0.5f,-0.5f,zn(0.0f))); + for(int i=0; i<4; i++){xyp.setColor(i, new Color3f(1.0f,1.0f,1.0f));} + + PolygonAttributes attrib = new PolygonAttributes(); + attrib.setCullFace(PolygonAttributes.CULL_NONE); + attrib.setPolygonMode(PolygonAttributes.POLYGON_FILL); + + TransparencyAttributes transAttrib; + float tr; + if(addXYPlane){ tr= 0.6f; } else { tr=1.0f; } + transAttrib = new TransparencyAttributes(TransparencyAttributes.NICEST,tr); + + Appearance appear = new Appearance(); + appear.setPolygonAttributes(attrib); + appear.setTransparencyAttributes(transAttrib); + appear.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_READ); + appear.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_WRITE); + + Shape3D xyplaneshape=new Shape3D(); + xyplaneshape.removeGeometry(0); + xyplaneshape.addGeometry(xyp); + xyplaneshape.setAppearance(appear); + xyplaneshape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); + xyplaneshape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); + + return xyplaneshape; + } + + //axes + private Shape3D axes(){ + LineArray a=new LineArray(6,LineArray.COORDINATES|LineArray.COLOR_3); + a.setCoordinate(0,new Point3f(0.6f,yn(0.0f),zn(0.0f))); + a.setCoordinate(1,new Point3f(-0.6f,yn(0.0f),zn(0.0f))); + a.setCoordinate(2,new Point3f(xn(0.0f),0.6f,zn(0.0f))); + a.setCoordinate(3,new Point3f(xn(0.0f),-0.6f,zn(0.0f))); + a.setCoordinate(4,new Point3f(xn(0.0f),yn(0.0f),0.6f)); + a.setCoordinate(5,new Point3f(xn(0.0f),yn(0.0f),-0.6f)); + for(int i=0; i<6; i++){ a.setColor(i,new Color3f(1.0f,1.0f,0.0f));} + + LineAttributes att=new LineAttributes(); + att.setLineWidth(2.0f); + Appearance appear = new Appearance(); + appear.setLineAttributes(att); + + Shape3D ax=new Shape3D(); + ax.removeGeometry(0); + ax.addGeometry(a); + ax.setAppearance(appear); + + return ax; + } + + //arrowhead + private Shape3D arrowhead(){ + int scounts[]= new int[3]; + for(int i=0; i<3; i++){scounts[i]=10;} + + TriangleFanArray ah=new TriangleFanArray(30, + TriangleFanArray.COORDINATES|TriangleFanArray.COLOR_3, + scounts); + ah.setCoordinate(0,new Point3f(0.6f, yn(0.0f), zn(0.0f))); + ah.setCoordinate(10,new Point3f(xn(0.0f),0.6f, zn(0.0f))); + ah.setCoordinate(20,new Point3f(xn(0.0f), yn(0.0f), 0.6f)); + float d=(float)Math.PI/4; + for(int i=0 ; i<=8; i++){ + ah.setCoordinate(i+1, + new Point3f(0.55f, yn(0.0f)+0.02f * (float)Math.cos(d*i), zn(0.0f)+0.02f *(float)Math.sin(d*i))); + ah.setCoordinate(i+11, + new Point3f(xn(0.0f)+0.02f * (float)Math.cos(d*i), 0.55f, zn(0.0f)+0.02f *(float)Math.sin(d*i))); + ah.setCoordinate(i+21, + new Point3f(xn(0.0f)+0.02f * (float)Math.cos(d*i), yn(0.0f)+0.02f *(float)Math.sin(d*i), 0.55f)); + } + Color3f color[]=new Color3f[30]; + for(int i=0; i<30; i++){ color[i]=new Color3f(1.0f, 1.0f, 0.0f);} + ah.setColors(0,color); + + return new Shape3D(ah); + } + + //axes labels + TransformGroup axeslabels(){ + TransformGroup tmp = new TransformGroup(); + + PolygonAttributes polyAttrib = new PolygonAttributes(); + polyAttrib.setCullFace(PolygonAttributes.CULL_NONE); + polyAttrib.setBackFaceNormalFlip(true); + + Transform3D xmov= (new Transform3D()); + xmov.set(new Vector3f(0.63f,yn(0.0f)-0.05f,zn(0.0f))); + Text2D xlbl=new Text2D("x",new Color3f(1.0f,1.0f,0.0f),"Helvetica",24,Font.BOLD); + (xlbl.getAppearance()).setPolygonAttributes(polyAttrib); + TransformGroup xmovg=new TransformGroup(xmov); + xmovg.addChild(xlbl); + + Transform3D ymov= new Transform3D(); + Transform3D tmpymov=new Transform3D(); + tmpymov.rotZ(Math.PI/2.0d); + ymov.set(new Vector3f(xn(0.0f)+0.05f,0.63f,zn(0.0f))); + ymov.mul(tmpymov); + Text2D ylbl=new Text2D("y",new Color3f(1.0f,1.0f,0.0f),"Helvetica",24,Font.BOLD); + (ylbl.getAppearance()).setPolygonAttributes(polyAttrib); + TransformGroup ymovg=new TransformGroup(ymov); + ymovg.addChild(ylbl); + + Transform3D zmov= new Transform3D(); + Transform3D tmpzmov=new Transform3D(); + tmpzmov.rotX(Math.PI/2.0d); + zmov.set(new Vector3f(xn(0.0f)-0.02f,yn(0.0f),0.63f)); + zmov.mul(tmpzmov); + Text2D zlbl=new Text2D("z",new Color3f(1.0f,1.0f,0.0f),"Helvetica",24,Font.BOLD); + (zlbl.getAppearance()).setPolygonAttributes(polyAttrib); + TransformGroup zmovg=new TransformGroup(zmov); + zmovg.addChild(zlbl); + + tmp.addChild(xmovg); + tmp.addChild(ymovg); + tmp.addChild(zmovg); + + return tmp; + } + + //get normalized coordinate + float xn(float x){ return (x-x0)/xwidth;} + float yn(float y){ return (y-y0)/ywidth;} + float zn(float z){ return (z-z0)/zwidth;} + + //////////// main class /////////////// + public graph3d() { + // preparation for numeric data + xwidth=xmax-xmin; + x0=(xmax+xmin)/2; + ywidth=ymax-ymin; + y0=(ymax+ymin)/2; + xdelta=xwidth/n; + ydelta=ywidth/n; + + zvalue = new float[n+1][n+1]; + zcenter = new float[n][n]; + + int i; int j; + + for(i=0; i<=n; i++){ + for(j=0; j<=n; j++){ + zvalue[i][j]=f(xmin+i*xdelta, ymin+j*ydelta); + } + } + for(i=0; i + + + Apple + Good + + + + Beer + Bitter + + + + Whiskey + + diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/saxtest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/saxtest.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,62 @@ +import javax.xml.parsers.*; +import org.xml.sax.*; +import org.xml.sax.helpers.*; +import java.io.*; + +public class saxtest extends DefaultHandler { + public static void main(String[] argv) { + try { + // SAXパーサーファクトリを生成 + SAXParserFactory spfactory = SAXParserFactory.newInstance(); + // SAXパーサーを生成 + SAXParser parser = spfactory.newSAXParser(); + // XMLファイルを指定されたデフォルトハンドラーで処理 + parser.parse(new File("src/example.graffle"), new HelloWorldSax()); + } catch (Exception e) { + e.printStackTrace(); + } + } + /** + * ドキュメント開始時 + */ + public void startDocument() { + System.out.println("ドキュメント開始"); + } + /** + * 要素の開始タグ読み込み時 + */ + public void startElement(String uri, + String localName, + String qName, + Attributes attributes) { + if( qName == "key" ){ + + System.out.println("要素開始:" + qName); + } + } + + /** + * テキストデータ読み込み時 + */ + public void characters(char[] ch, + int offset, + int length) { + + System.out.println("テキストデータ:" + new String(ch, offset, length)); + } + /** + * 要素の終了タグ読み込み時 + */ + public void endElement(String uri, + String localName, + String qName) { + + System.out.println("要素終了:" + qName); + } + /** + * ドキュメント終了時 + */ + public void endDocument() { + System.out.println("ドキュメント終了"); + } +} \ No newline at end of file diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/select_key_xml.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/select_key_xml.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,55 @@ +import org.xml.sax.*; +import org.xml.sax.helpers.*; + +class select_key_xml extends DefaultHandler{ +// private String currentTag; + + /* XML文書の開始時の処理*/ + public void startDocument(){ + System.out.println("Here is start of XML document."); + } + + /* 要素の開始時の処理*/ + public void startElement(String qName){ + System.out.println("Start Element"); + + /*タグ名を表示*/ + if(qName != ""){ + System.out.println("qName= "+qName); +// currentTag=qName; + } + } + + /*要素の終了時の処理*/ + public void endElement(String qName){ + System.out.println("End element."); + if(qName!=""){ + System.out.println("qName= "+qName); + } +// currentTag=""; + } + + /* XML文書の終了時の処理*/ + public void endDocument(){ + System.out.println("Here is end of XML document."); + } + + /* 文字列の処理*/ + public void characters(char[] ch,int start,int length){ + String str=new String(ch,start,length); + if(str.length()!=0){ + System.out.println("====="+str+"====="); + } + } + + /* 処理命令を受けた時の処理 要調査*/ + public void processingInstruction(String target,String data){} + + /* プレフィックスによる名前空間の範囲の開始時 要調査*/ + public void startPrefixMapping(String prefix,String uri){} + + /* プレフィックスによる名前空間の範囲の終了時 要調査*/ + public void endPrefixMapping(String prefix){} + + +} diff -r 1bcc0070c2f6 -r 226c97efb693 tools/java3d-test/src/two_obj.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/java3d-test/src/two_obj.java Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,143 @@ +import java.applet.Applet; +import com.sun.j3d.utils.applet.MainFrame; +//import com.sun.j3d.utils.behaviors.mouse.*; +//import com.sun.j3d.utils.behaviors.keyboard.*; + +import javax.media.j3d.*; + +import java.awt.BorderLayout; + +import java.awt.GraphicsConfiguration; +import com.sun.j3d.utils.universe.*; +import com.sun.j3d.utils.geometry.*; +import javax.vecmath.*; + +import java.awt.*; +import java.awt.geom.*; +import java.awt.event.*; +import javax.swing.*; +import java.awt.image.BufferedImage; +import java.io.File; +import javax.imageio.ImageIO; +import java.io.IOException; + + + +public class two_obj extends Applet { + + public SimpleUniverse universe = null; + public Canvas3D canvas = null; + + public BranchGroup createObjects(){ + BranchGroup root = new BranchGroup(); + + root.addChild(createLight()); + + Appearance ap = new Appearance(); + Material ma = new Material(); + ma.setDiffuseColor(0.0f, 0.0f, 1.0f); + ap.setMaterial(ma); + + + + + //TransformGroup transRoot = new TransformGroup(); + //Transform3D transform = new Transform3D(); + TransformGroup td3Root = addobj(new Vector3d(1.0, 0.0, 0.0)); + root.addChild(td3Root); + TransformGroup td3Root1 = addobj(new Vector3d(0.0, 0.0, 0.0)); + root.addChild(td3Root1); + TransformGroup td3Root2 = addobj(new Vector3d(-1.0, 1.0, 0.0)); + root.addChild(td3Root2); + +// //View用TransfromGroup +// //全体を見渡す巨大で透明なSphireを作る +// TransformGroup viewSphire = new TransformGroup(); +// viewSphire.addChild(new Sphere(50.f)); +// +// viewSphire.setCapability( TransformGroup.ALLOW_TRANSFORM_READ ); +// viewSphire.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE ); +// +// MouseRotate rotat = new MouseRotate( viewSphire ); +// MouseTranslate trans = new MouseTranslate( viewSphire ); +// MouseZoom zoom = new MouseZoom( viewSphire ); +// +// BoundingSphere bounds = new BoundingSphere(); +// +// bounds.setRadius( 10.0 ); +// rotat.setSchedulingBounds( bounds ); +// trans.setSchedulingBounds( bounds ); +// zoom.setSchedulingBounds( bounds ); +// +// td3Root.addChild(rotat); +// td3Root.addChild(trans); +// td3Root.addChild(zoom); + + //transform.set(new Vector3d(1.0, 0.0, 0.0)); + //transRoot.setTransform(transform); + + //transRoot.addChild(new ColorCube(0.4)); + //root.addChild(transRoot); + +// root.addChild(new ColorCube(0.4)); + root.compile(); + + return root; + + } + + private Light createLight(){ + DirectionalLight light = new DirectionalLight( true, + new Color3f(0.0f, 0.0f, 1.0f), + new Vector3f(0.0f, 0.0f, -1.0f)); + + light.setInfluencingBounds(new BoundingSphere(new Point3d(), 100.0)); + + return light; + } + + + + private TransformGroup addobj(Vector3d vec3d) { + TransformGroup td3Root = new TransformGroup(); + Transform3D t3d = new Transform3D(); + t3d.setTranslation(vec3d); + td3Root.setTransform(t3d); + td3Root.addChild(new Sphere(0.3f, Sphere.GENERATE_NORMALS, 50)); + return td3Root; + } + +// public void setOrbitBehavior() { +// +// // マウスでぐりぐりするための処理 +// OrbitBehavior orbit = new OrbitBehavior(canvas, OrbitBehavior.REVERSE_ALL); +// orbit.setSchedulingBounds( +// new BoundingSphere(new Point3d(0, 0, 0), 100.0)); +// universe.getViewingPlatform().setViewPlatformBehavior(orbit); +// } + + public void init() { + setLayout(new BorderLayout()); + + GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration(); + + Canvas3D canvas = new Canvas3D(config); + + add("Center", canvas); + + universe = new SimpleUniverse(canvas); + + universe.getViewingPlatform().setNominalViewingTransform(); + + // マウスでぐりぐり動かすための処理 +// setOrbitBehavior(); + + universe.addBranchGraph(createObjects()); + } + + public static void main(String[] args) { + new MainFrame(new two_obj(), 600, 600); + } + +} + diff -r 1bcc0070c2f6 -r 226c97efb693 tools/pexpect.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/tools/pexpect.py Sun Dec 20 11:44:21 2009 +0900 @@ -0,0 +1,1203 @@ +"""Pexpect is a Python module for spawning child applications; +controlling them; and responding to expected patterns in their output. +Pexpect can be used for automating interactive applications such as +ssh, ftp, passwd, telnet, etc. It can be used to a automate setup scripts +for duplicating software package installations on different servers. +It can be used for automated software testing. Pexpect is in the spirit of +Don Libes' Expect, but Pexpect is pure Python. Other Expect-like +modules for Python require TCL and Expect or require C extensions to +be compiled. Pexpect does not use C, Expect, or TCL extensions. It +should work on any platform that supports the standard Python pty +module. The Pexpect interface focuses on ease of use so that simple +tasks are easy. + +There are two main interfaces to Pexpect. You can call the function: + pexpect.run() +to execute a command and return the output. +Do no use this on interactive commands that expect input. +This is a handy replacment for os.system(). +The more useful interface is the class: + pexpect.spawn() +This creates a spawn instance. This will start the command that you specify. +You can then interact with the child command through the spawn instance. +Most commands, including ssh, cannot tell that they are being run inside +of a script. This works even for commands that ask for passwords or +other input outside of the normal stdio streams. + +Pexpect is Open Source, Free, and all that good stuff. +License: Python Software Foundation License + http://www.opensource.org/licenses/PythonSoftFoundation.html + +Noah Spurrier +Richard Holden +Marco Molteni +Kimberley Burchett +Robert Stone +Mike Snitzer +Marti Raudsepp +Matt +Hartmut Goebel +Chad Schroeder +Erick Tryzelaar +Dave Kirby +Ids vander Molen +George Todd +Noel Taylor +Nicolas D. Cesar +(Let me know if I forgot anyone.) + +$Revision: 1.1.1.1 $ +$Date: 2006/04/01 06:03:29 $ +""" + +try: + import os, sys, time + import select + import string + import re + import struct + import resource + import types + import pty + import tty + import termios + import fcntl + import errno + import traceback + import signal +except ImportError, e: + raise ImportError (str(e) + """ +A critical module was not found. Probably this operating system does not support it. +Pexpect is intended for UNIX-like operating systems.""") + +__version__ = '2.0' +__revision__ = '$Revision: 1.1.1.1 $' +__all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'run', 'which', 'split_command_line', + '__version__', '__revision__'] + +# Exception classes used by this module. +class ExceptionPexpect(Exception): + """Base class for all exceptions raised by this module. + """ + def __init__(self, value): + self.value = value + def __str__(self): + return str(self.value) + def get_trace(self): + """This returns an abbreviated stack trace with lines that only concern the caller. + In other words, the stack trace inside the Pexpect module is not included. + """ + tblist = traceback.extract_tb(sys.exc_info()[2]) + tblist = filter(self.__filter_not_pexpect, tblist) + tblist = traceback.format_list(tblist) + return ''.join(tblist) + def __filter_not_pexpect(self, trace_list_item): + if trace_list_item[0].find('pexpect.py') == -1: + return 1 + else: + return 0 +class EOF(ExceptionPexpect): + """Raised when EOF is read from a child. + """ +class TIMEOUT(ExceptionPexpect): + """Raised when a read time exceeds the timeout. + """ +##class TIMEOUT_PATTERN(TIMEOUT): +## """Raised when the pattern match time exceeds the timeout. +## This is different than a read TIMEOUT because the child process may +## give output, thus never give a TIMEOUT, but the output +## may never match a pattern. +## """ +##class MAXBUFFER(ExceptionPexpect): +## """Raised when a scan buffer fills before matching an expected pattern.""" + +def run (command, timeout=-1, withexitstatus=0, events=None, extra_args=None): + """This function runs the given command; waits for it to finish; + then returns all output as a string. STDERR is included in output. + If the full path to the command is not given then the path is searched. + + Note that lines are terminated by CR/LF (\\r\\n) combination + even on UNIX-like systems because this is the standard for pseudo ttys. + If you set withexitstatus to true, then run will return a tuple of + (command_output, exitstatus). If withexitstatus is false then this + returns just command_output. + + Examples: + Start the apache daemon on the local machine: + from pexpect import * + run ("/usr/local/apache/bin/apachectl start") + Check in a file using SVN: + from pexpect import * + run ("svn ci -m 'automatic commit' my_file.py") + Run a command and capture exit status: + from pexpect import * + (command_output, exitstatus) = run ('ls -l /bin', withexitstatus=1) + + Tricky Examples: + The following will run SSH and execute 'ls -l' on the remote machine. + The password 'secret' will be sent if the '(?i)password' pattern is ever seen. + run ("ssh username@machine.example.com 'ls -l'", events={'(?i)password':'secret\n'}) + + This will start mencoder to rip a video from DVD. This will also display + progress ticks every 5 seconds as it runs. + from pexpect import * + def print_ticks(d): + print d['event_count'], + run ("mencoder dvd://1 -o video.avi -oac copy -ovc copy", events={TIMEOUT:print_ticks}, timeout=5) + + The 'events' argument should be a dictionary of patterns and responses. + Whenever one of the patterns is seen in the command out + run() will send the associated response string. Note that you should + put newlines in your string if Enter is necessary. + The responses may also contain callback functions. + Any callback is function that takes a dictionary as an argument. + The dictionary contains all the locals from the run() function, so + you can access the child spawn object or any other variable defined + in run() (event_count, child, and extra_args are the most useful). + A callback may return True to stop the current run process otherwise + run() continues until the next event. + A callback may also return a string which will be sent to the child. + 'extra_args' is not used by directly run(). It provides a way to pass data to + a callback function through run() through the locals dictionary passed to a callback. + """ + if timeout == -1: + child = spawn(command, maxread=2000) + else: + child = spawn(command, timeout=timeout, maxread=2000) + if events is not None: + patterns = events.keys() + responses = events.values() + else: + patterns=None # We assume that EOF or TIMEOUT will save us. + responses=None + child_result_list = [] + event_count = 0 + while 1: + try: + index = child.expect (patterns) + if type(child.after) is types.StringType: + child_result_list.append(child.before + child.after) + else: # child.after may have been a TIMEOUT or EOF, so don't cat those. + child_result_list.append(child.before) + if type(responses[index]) is types.StringType: + child.send(responses[index]) + elif type(responses[index]) is types.FunctionType: + callback_result = responses[index](locals()) + sys.stdout.flush() + if type(callback_result) is types.StringType: + child.send(callback_result) + elif callback_result: + break + else: + raise TypeError ('The callback must be a string or function type.') + event_count = event_count + 1 + except TIMEOUT, e: + child_result_list.append(child.before) + break + except EOF, e: + child_result_list.append(child.before) + break + child_result = ''.join(child_result_list) + if withexitstatus: + child.close() + return (child_result, child.exitstatus) + else: + return child_result + +class spawn: + """This is the main class interface for Pexpect. + Use this class to start and control child applications. + """ + + def __init__(self, command, args=[], timeout=30, maxread=2000, searchwindowsize=None, logfile=None): + """This is the constructor. The command parameter may be a string + that includes a command and any arguments to the command. For example: + p = pexpect.spawn ('/usr/bin/ftp') + p = pexpect.spawn ('/usr/bin/ssh user@example.com') + p = pexpect.spawn ('ls -latr /tmp') + You may also construct it with a list of arguments like so: + p = pexpect.spawn ('/usr/bin/ftp', []) + p = pexpect.spawn ('/usr/bin/ssh', ['user@example.com']) + p = pexpect.spawn ('ls', ['-latr', '/tmp']) + After this the child application will be created and + will be ready to talk to. For normal use, see expect() and + send() and sendline(). + + The maxread attribute sets the read buffer size. + This is maximum number of bytes that Pexpect will try to read from a TTY at one time. + The default buffer size is 1 (unbuffered). Setting this value higher + will help performance in cases where large amounts of output are read back from the child. + This feature is useful in conjunction with searchwindowsize. + + The searchwindowsize attribute sets the how far back in + the incomming seach buffer Pexpect will search for pattern matches. + Every time Pexpect reads some data from the child it will append the data to + the incomming buffer. The default is to search from the beginning of the + imcomming buffer each time new data is read from the child. + But this is very inefficient if you are running a command that + generates a large amount of data where you want to match + The searchwindowsize does not effect the size of the incomming data buffer. + You will still have access to the full buffer after expect() returns. + + The logfile member turns on or off logging. + All input and output will be copied to the given file object. + Set logfile to None to stop logging. This is the default. + Set logfile to sys.stdout to echo everything to standard output. + The logfile is flushed after each write. + Example 1: + child = pexpect.spawn('some_command') + fout = file('mylog.txt','w') + child.logfile = fout + Example 2: + child = pexpect.spawn('some_command') + child.logfile = sys.stdout + + The delaybeforesend helps overcome weird behavior that many users were experiencing. + The typical problem was that a user would expect() a "Password:" prompt and + then immediately call sendline() to send the password. The user would then + see that their password was echoed back to them. Of course, passwords don't + normally echo. The problem is caused by the fact that most applications + print out the "Password" prompt and then turn off stdin echo, but if you + send your password before the application turned off echo, then you get + your password echoed. Normally this wouldn't be a problem when interacting + with a human at a real heyboard. If you introduce a slight delay just before + writing then this seems to clear up the problem. This was such a common problem + for many users that I decided that the default pexpect behavior + should be to sleep just before writing to the child application. + 1/10th of a second (100 ms) seems to be enough to clear up the problem. + You can set delaybeforesend to 0 to return to the old behavior. + + Note that spawn is clever about finding commands on your path. + It uses the same logic that "which" uses to find executables. + + If you wish to get the exit status of the child you must call + the close() method. The exit or signal status of the child will be + stored in self.exitstatus or self.signalstatus. + If the child exited normally then exitstatus will store the exit return code and + signalstatus will be None. + If the child was terminated abnormally with a signal then signalstatus will store + the signal value and exitstatus will be None. + If you need more detail you can also read the self.status member which stores + the status returned by os.waitpid. You can interpret this using + os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. + """ + self.STDIN_FILENO = pty.STDIN_FILENO + self.STDOUT_FILENO = pty.STDOUT_FILENO + self.STDERR_FILENO = pty.STDERR_FILENO + self.stdin = sys.stdin + self.stdout = sys.stdout + self.stderr = sys.stderr + + self.patterns = None + self.before = None + self.after = None + self.match = None + self.match_index = None + self.terminated = 1 + self.exitstatus = None + self.signalstatus = None + self.status = None + self.flag_eof = 0 + self.pid = None + self.child_fd = -1 # initially closed + self.timeout = timeout + self.delimiter = EOF + self.logfile = logfile + self.maxread = maxread # Max bytes to read at one time into buffer. + self.buffer = '' # This is the read buffer. See maxread. + self.searchwindowsize = searchwindowsize # Anything before searchwindowsize point is preserved, but not searched. + self.delaybeforesend = 0.1 # Sets sleep time used just before sending data to child. + self.softspace = 0 # File-like object. + self.name = '<' + repr(self) + '>' # File-like object. + self.encoding = None # File-like object. + self.closed = 1 # File-like object. + + if type (args) != type([]): + raise TypeError ('The second argument, args, must be a list.') + + if args == []: + self.args = split_command_line(command) + self.command = self.args[0] + else: + self.args = args[:] # work with a copy + self.args.insert (0, command) + self.command = command + + command_with_path = which(self.command) + if command_with_path == None: + raise ExceptionPexpect ('The command was not found or was not executable: %s.' % self.command) + self.command = command_with_path + self.args[0] = self.command + + self.name = '<' + ' '.join (self.args) + '>' + self.__spawn() + + def __del__(self): + """This makes sure that no system resources are left open. + Python only garbage collects Python objects. OS file descriptors + are not Python objects, so they must be handled explicitly. + If the child file descriptor was opened outside of this class + (passed to the constructor) then this does not close it. + """ + if self.closed: + return + self.close() + + def __str__(self): + """This returns the current state of the pexpect object as a string. + """ + s = [] + s.append(repr(self)) + s.append('version: ' + __version__ + ' (' + __revision__ + ')') + s.append('command: ' + str(self.command)) + s.append('args: ' + str(self.args)) + if self.patterns is None: + s.append('patterns: None') + else: + s.append('patterns:') + for p in self.patterns: + if type(p) is type(re.compile('')): + s.append(' ' + str(p.pattern)) + else: + s.append(' ' + str(p)) + s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:]) + s.append('before (last 100 chars): ' + str(self.before)[-100:]) + s.append('after: ' + str(self.after)) + s.append('match: ' + str(self.match)) + s.append('match_index: ' + str(self.match_index)) + s.append('exitstatus: ' + str(self.exitstatus)) + s.append('flag_eof: ' + str(self.flag_eof)) + s.append('pid: ' + str(self.pid)) + s.append('child_fd: ' + str(self.child_fd)) + s.append('timeout: ' + str(self.timeout)) + s.append('delimiter: ' + str(self.delimiter)) + s.append('logfile: ' + str(self.logfile)) + s.append('maxread: ' + str(self.maxread)) + s.append('searchwindowsize: ' + str(self.searchwindowsize)) + s.append('delaybeforesend: ' + str(self.delaybeforesend)) + return '\n'.join(s) + + def __spawn(self): + """This starts the given command in a child process. + This does all the fork/exec type of stuff for a pty. + This is called by __init__. + """ + # The pid and child_fd of this object get set by this method. + # Note that it is difficult for this method to fail. + # You cannot detect if the child process cannot start. + # So the only way you can tell if the child process started + # or not is to try to read from the file descriptor. If you get + # EOF immediately then it means that the child is already dead. + # That may not necessarily be bad because you may haved spawned a child + # that performs some task; creates no stdout output; and then dies. + + assert self.pid == None, 'The pid member should be None.' + assert self.command != None, 'The command member should not be None.' + + try: + self.pid, self.child_fd = pty.fork() + except OSError, e: + raise ExceptionPexpect('Pexpect: pty.fork() failed: ' + str(e)) + + if self.pid == 0: # Child + try: # Some platforms do not like setwinsize (Cygwin). + self.child_fd = sys.stdout.fileno() # used by setwinsize() + self.setwinsize(24, 80) + except: + pass + # Do not allow child to inherit open file descriptors from parent. + max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0] + for i in range (3, max_fd): + try: + os.close (i) + except OSError: + pass + + # I don't know why this works, but ignoring SIGHUP fixes a + # problem when trying to start a Java daemon with sudo + # (specifically, Tomcat). + signal.signal(signal.SIGHUP, signal.SIG_IGN) + + os.execv(self.command, self.args) + + # Parent + self.terminated = 0 + self.closed = 0 + + def fileno (self): # File-like object. + """This returns the file descriptor of the pty for the child. + """ + return self.child_fd + + def close (self, force=0): # File-like object. + """This closes the connection with the child application. + Note that calling close() more than once is valid. + This emulates standard Python behavior with files. + Set force to 1 if you want to make sure that the child is terminated + (SIGKILL is sent if the child ignores SIGHUP and SIGINT). + """ + if self.child_fd != -1: + self.flush() + os.close (self.child_fd) + self.child_fd = -1 + self.closed = 1 + time.sleep(0.1) # Give kernel time to update process status. + if self.isalive(): + if not self.terminate(force): + raise ExceptionPexpect ('close() could not terminate the child using terminate()') + + def flush (self): # File-like object. + """This does nothing. It is here to support the interface for a File-like object. + """ + pass + + def isatty (self): # File-like object. + """This returns 1 if the file descriptor is open and connected to a tty(-like) device, else 0. + """ + return os.isatty(self.child_fd) + + def setecho (self, on): + """This sets the terminal echo mode on or off. + Note that anything the child sent before the echo will be lost, so + you should be sure that your input buffer is empty before you setecho. + For example, the following will work as expected. + p = pexpect.spawn('cat') + p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). + p.expect (['1234']) + p.expect (['1234']) + p.setecho(0) # Turn off tty echo + p.sendline ('abcd') # We will set this only once (echoed by cat). + p.sendline ('wxyz') # We will set this only once (echoed by cat) + p.expect (['abcd']) + p.expect (['wxyz']) + The following WILL NOT WORK because the lines sent before the setecho + will be lost: + p = pexpect.spawn('cat') + p.sendline ('1234') # We will see this twice (once from tty echo and again from cat). + p.setecho(0) # Turn off tty echo + p.sendline ('abcd') # We will set this only once (echoed by cat). + p.sendline ('wxyz') # We will set this only once (echoed by cat) + p.expect (['1234']) + p.expect (['1234']) + p.expect (['abcd']) + p.expect (['wxyz']) + """ + self.child_fd + new = termios.tcgetattr(self.child_fd) + if on: + new[3] = new[3] | termios.ECHO + else: + new[3] = new[3] & ~termios.ECHO + # I tried TCSADRAIN and TCSAFLUSH, but these were inconsistent + # and blocked on some platforms. TCSADRAIN is probably ideal if it worked. + termios.tcsetattr(self.child_fd, termios.TCSANOW, new) + + def read_nonblocking (self, size = 1, timeout = -1): + """This reads at most size characters from the child application. + It includes a timeout. If the read does not complete within the + timeout period then a TIMEOUT exception is raised. + If the end of file is read then an EOF exception will be raised. + If a log file was set using setlog() then all data will + also be written to the log file. + + If timeout==None then the read may block indefinitely. + If timeout==-1 then the self.timeout value is used. + If timeout==0 then the child is polled and + if there was no data immediately ready then this will raise a TIMEOUT exception. + + The "timeout" refers only to the amount of time to read at least one character. + This is not effected by the 'size' parameter, so if you call + read_nonblocking(size=100, timeout=30) and only one character is + available right away then one character will be returned immediately. + It will not wait for 30 seconds for another 99 characters to come in. + + This is a wrapper around os.read(). + It uses select.select() to implement a timeout. + """ + if self.child_fd == -1: + raise ValueError ('I/O operation on closed file in read_nonblocking().') + + if timeout == -1: + timeout = self.timeout + + # Note that some systems such as Solaris do not give an EOF when + # the child dies. In fact, you can still try to read + # from the child_fd -- it will block forever or until TIMEOUT. + # For this case, I test isalive() before doing any reading. + # If isalive() is false, then I pretend that this is the same as EOF. + if not self.isalive(): + r, w, e = select.select([self.child_fd], [], [], 0) # timeout of 0 means "poll" + if not r: + self.flag_eof = 1 + raise EOF ('End Of File (EOF) in read_nonblocking(). Braindead platform.') + elif sys.platform.lower().find('irix') >= 0: + # This is a hack for Irix. It seems that Irix requires a long delay before checking isalive. + # This adds a 2 second delay, but only when the child is terminated + r, w, e = select.select([self.child_fd], [], [], 2) + if not r and not self.isalive(): + self.flag_eof = 1 + raise EOF ('End Of File (EOF) in read_nonblocking(). Pokey platform.') + + r, w, e = select.select([self.child_fd], [], [], timeout) + if not r: + if not self.isalive(): + # Some platforms, such as Irix, will claim that their processes are alive; + # then timeout on the select; and then finally admit that they are not alive. + self.flag_eof = 1 + raise EOF ('End of File (EOF) in read_nonblocking(). Very pokey platform.') + else: + raise TIMEOUT ('Timeout exceeded in read_nonblocking().') + + if self.child_fd in r: + try: + s = os.read(self.child_fd, size) + except OSError, e: # Linux does this + self.flag_eof = 1 + raise EOF ('End Of File (EOF) in read_nonblocking(). Exception style platform.') + if s == '': # BSD style + self.flag_eof = 1 + raise EOF ('End Of File (EOF) in read_nonblocking(). Empty string style platform.') + + if self.logfile != None: + self.logfile.write (s) + self.logfile.flush() + + return s + + raise ExceptionPexpect ('Reached an unexpected state in read_nonblocking().') + + def read (self, size = -1): # File-like object. + """This reads at most "size" bytes from the file + (less if the read hits EOF before obtaining size bytes). + If the size argument is negative or omitted, + read all data until EOF is reached. + The bytes are returned as a string object. + An empty string is returned when EOF is encountered immediately. + """ + if size == 0: + return '' + if size < 0: + self.expect (self.delimiter) # delimiter default is EOF + return self.before + + # I could have done this more directly by not using expect(), but + # I deliberately decided to couple read() to expect() so that + # I would catch any bugs early and ensure consistant behavior. + # It's a little less efficient, but there is less for me to + # worry about if I have to later modify read() or expect(). + # Note, it's OK if size==-1 in the regex. That just means it + # will never match anything in which case we stop only on EOF. + cre = re.compile('.{%d}' % size, re.DOTALL) + index = self.expect ([cre, self.delimiter]) # delimiter default is EOF + if index == 0: + return self.after ### self.before should be ''. Should I assert this? + return self.before + + def readline (self, size = -1): # File-like object. + """This reads and returns one entire line. A trailing newline is kept in + the string, but may be absent when a file ends with an incomplete line. + Note: This readline() looks for a \\r\\n pair even on UNIX because this is + what the pseudo tty device returns. So contrary to what you may be used to + you will receive a newline as \\r\\n. + An empty string is returned when EOF is hit immediately. + Currently, the size agument is mostly ignored, so this behavior is not + standard for a file-like object. If size is 0 then an empty string is returned. + """ + if size == 0: + return '' + index = self.expect (['\r\n', self.delimiter]) # delimiter default is EOF + if index == 0: + return self.before + '\r\n' + else: + return self.before + + def __iter__ (self): # File-like object. + """This is to support interators over a file-like object. + """ + return self + + def next (self): # File-like object. + """This is to support iterators over a file-like object. + """ + result = self.readline() + if result == "": + raise StopIteration + return result + + def readlines (self, sizehint = -1): # File-like object. + """This reads until EOF using readline() and returns a list containing + the lines thus read. The optional "sizehint" argument is ignored. + """ + lines = [] + while 1: + line = self.readline() + if not line: + break + lines.append(line) + return lines + + def write(self, str): # File-like object. + """This is similar to send() except that there is no return value. + """ + self.send (str) + + def writelines (self, sequence): # File-like object. + """This calls write() for each element in the sequence. + The sequence can be any iterable object producing strings, + typically a list of strings. This does not add line separators + There is no return value. + """ + for str in sequence: + self.write (str) + + def send(self, str): + """This sends a string to the child process. + This returns the number of bytes written. + If a log file was set then the data is also written to the log. + """ + time.sleep(self.delaybeforesend) + if self.logfile != None: + self.logfile.write (str) + self.logfile.flush() + c = os.write(self.child_fd, str) + return c + + def sendline(self, str=''): + """This is like send(), but it adds a line feed (os.linesep). + This returns the number of bytes written. + """ + n = self.send(str) + n = n + self.send (os.linesep) + return n + + def sendeof(self): + """This sends an EOF to the child. + This sends a character which causes the pending parent output + buffer to be sent to the waiting child program without + waiting for end-of-line. If it is the first character of the + line, the read() in the user program returns 0, which + signifies end-of-file. This means to work as expected + a sendeof() has to be called at the begining of a line. + This method does not send a newline. It is the responsibility + of the caller to ensure the eof is sent at the beginning of a line. + """ + ### Hmmm... how do I send an EOF? + ###C if ((m = write(pty, *buf, p - *buf)) < 0) + ###C return (errno == EWOULDBLOCK) ? n : -1; + fd = sys.stdin.fileno() + old = termios.tcgetattr(fd) # remember current state + new = termios.tcgetattr(fd) + new[3] = new[3] | termios.ICANON # ICANON must be set to recognize EOF + try: # use try/finally to ensure state gets restored + termios.tcsetattr(fd, termios.TCSADRAIN, new) + if 'CEOF' in dir(termios): + os.write (self.child_fd, '%c' % termios.CEOF) + else: + os.write (self.child_fd, '%c' % 4) # Silly platform does not define CEOF so assume CTRL-D + finally: # restore state + termios.tcsetattr(fd, termios.TCSADRAIN, old) + + def eof (self): + """This returns 1 if the EOF exception was raised at some point. + """ + return self.flag_eof + + def terminate(self, force=0): + """This forces a child process to terminate. + It starts nicely with SIGHUP and SIGINT. If "force" is 1 then + moves onto SIGKILL. + This returns true if the child was terminated. + This returns false if the child could not be terminated. + """ + if not self.isalive(): + return 1 + self.kill(signal.SIGHUP) + time.sleep(0.1) + if not self.isalive(): + return 1 + self.kill(signal.SIGCONT) + time.sleep(0.1) + if not self.isalive(): + return 1 + self.kill(signal.SIGINT) + time.sleep(0.1) + if not self.isalive(): + return 1 + if force: + self.kill(signal.SIGKILL) + time.sleep(0.1) + if not self.isalive(): + return 1 + else: + return 0 + return 0 + #raise ExceptionPexpect ('terminate() could not terminate child process. Try terminate(force=1)?') + + def isalive(self): + """This tests if the child process is running or not. + This is non-blocking. If the child was terminated then this + will read the exitstatus or signalstatus of the child. + This returns 1 if the child process appears to be running or 0 if not. + It can take literally SECONDS for Solaris to return the right status. + """ + if self.terminated: + return 0 + + if self.flag_eof: + # This is for Linux, which requires the blocking form of waitpid to get + # status of a defunct process. This is super-lame. The flag_eof would have + # been set in read_nonblocking(), so this should be safe. + waitpid_options = 0 + else: + waitpid_options = os.WNOHANG + + try: + pid, status = os.waitpid(self.pid, waitpid_options) + except OSError, e: # No child processes + if e[0] == errno.ECHILD: + raise ExceptionPexpect ('isalive() encountered condition where "terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?') + else: + raise e + + # I have to do this twice for Solaris. I can't even believe that I figured this out... + # If waitpid() returns 0 it means that no child process wishes to + # report, and the value of status is undefined. + if pid == 0: + try: + pid, status = os.waitpid(self.pid, waitpid_options) ### os.WNOHANG) # Solaris! + except OSError, e: # This should never happen... + if e[0] == errno.ECHILD: + raise ExceptionPexpect ('isalive() encountered condition that should never happen. There was no child process. Did someone else call waitpid() on our process?') + else: + raise e + + # If pid is still 0 after two calls to waitpid() then + # the process really is alive. This seems to work on all platforms, except + # for Irix which seems to require a blocking call on waitpid or select, so I let read_nonblocking + # take care of this situation (unfortunately, this requires waiting through the timeout). + if pid == 0: + return 1 + + if pid == 0: + return 1 + + if os.WIFEXITED (status): + self.status = status + self.exitstatus = os.WEXITSTATUS(status) + self.signalstatus = None + self.terminated = 1 + return 0 + elif os.WIFSIGNALED (status): + self.status = status + self.exitstatus = None + self.signalstatus = os.WTERMSIG(status) + self.terminated = 1 + return 0 + elif os.WIFSTOPPED (status): + raise ExceptionPexpect ('isalive() encountered condition where child process is stopped. This is not supported. Is some other process attempting job control with our child pid?') + + raise ExceptionPexpect ('isalive() reached unexpected condition where waitpid matched child pid, but status was not matched by WIFEXITED, WIFSIGNALED, or WIFSTOPPED.') + + + def kill(self, sig): + """This sends the given signal to the child application. + In keeping with UNIX tradition it has a misleading name. + It does not necessarily kill the child unless + you send the right signal. + """ + # Same as os.kill, but the pid is given for you. + if self.isalive(): + os.kill(self.pid, sig) + + def compile_pattern_list(self, patterns): + """This compiles a pattern-string or a list of pattern-strings. + Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or + a list of those. Patterns may also be None which results in + an empty list. + + This is used by expect() when calling expect_list(). + Thus expect() is nothing more than:: + cpl = self.compile_pattern_list(pl) + return self.expect_list(clp, timeout) + + If you are using expect() within a loop it may be more + efficient to compile the patterns first and then call expect_list(). + This avoid calls in a loop to compile_pattern_list(): + cpl = self.compile_pattern_list(my_pattern) + while some_condition: + ... + i = self.expect_list(clp, timeout) + ... + """ + if patterns is None: + return [] + if type(patterns) is not types.ListType: + patterns = [patterns] + + compiled_pattern_list = [] + for p in patterns: + if type(p) is types.StringType: + compiled_pattern_list.append(re.compile(p, re.DOTALL)) + elif p is EOF: + compiled_pattern_list.append(EOF) + elif p is TIMEOUT: + compiled_pattern_list.append(TIMEOUT) + elif type(p) is type(re.compile('')): + compiled_pattern_list.append(p) + else: + raise TypeError ('Argument must be one of StringType, EOF, TIMEOUT, SRE_Pattern, or a list of those type. %s' % str(type(p))) + + return compiled_pattern_list + + def expect(self, pattern, timeout = -1, searchwindowsize=None): + """This seeks through the stream until a pattern is matched. + The pattern is overloaded and may take several types including a list. + The pattern can be a StringType, EOF, a compiled re, or + a list of those types. Strings will be compiled to re types. + This returns the index into the pattern list. If the pattern was + not a list this returns index 0 on a successful match. + This may raise exceptions for EOF or TIMEOUT. + To avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to + the pattern list. + + After a match is found the instance attributes + 'before', 'after' and 'match' will be set. + You can see all the data read before the match in 'before'. + You can see the data that was matched in 'after'. + The re.MatchObject used in the re match will be in 'match'. + If an error occured then 'before' will be set to all the + data read so far and 'after' and 'match' will be None. + + If timeout is -1 then timeout will be set to the self.timeout value. + + Note: A list entry may be EOF or TIMEOUT instead of a string. + This will catch these exceptions and return the index + of the list entry instead of raising the exception. + The attribute 'after' will be set to the exception type. + The attribute 'match' will be None. + This allows you to write code like this: + index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT]) + if index == 0: + do_something() + elif index == 1: + do_something_else() + elif index == 2: + do_some_other_thing() + elif index == 3: + do_something_completely_different() + instead of code like this: + try: + index = p.expect (['good', 'bad']) + if index == 0: + do_something() + elif index == 1: + do_something_else() + except EOF: + do_some_other_thing() + except TIMEOUT: + do_something_completely_different() + These two forms are equivalent. It all depends on what you want. + You can also just expect the EOF if you are waiting for all output + of a child to finish. For example: + p = pexpect.spawn('/bin/ls') + p.expect (pexpect.EOF) + print p.before + + If you are trying to optimize for speed then see expect_list(). + """ + compiled_pattern_list = self.compile_pattern_list(pattern) + return self.expect_list(compiled_pattern_list, timeout, searchwindowsize) + + def expect_list(self, pattern_list, timeout = -1, searchwindowsize = -1): + """This takes a list of compiled regular expressions and returns + the index into the pattern_list that matched the child's output. + The list may also contain EOF or TIMEOUT (which are not + compiled regular expressions). This method is similar to + the expect() method except that expect_list() does not + recompile the pattern list on every call. + This may help if you are trying to optimize for speed, otherwise + just use the expect() method. This is called by expect(). + If timeout==-1 then the self.timeout value is used. + If searchwindowsize==-1 then the self.searchwindowsize value is used. + """ + self.patterns = pattern_list + + if timeout == -1: + timeout = self.timeout + if timeout != None: + end_time = time.time() + timeout + if searchwindowsize == -1: + searchwindowsize = self.searchwindowsize + + try: + incoming = self.buffer + while 1: # Keep reading until exception or return. + # Sequence through the list of patterns looking for a match. + first_match = -1 + for cre in pattern_list: + if cre is EOF or cre is TIMEOUT: + continue # The patterns for PexpectExceptions are handled differently. + if searchwindowsize is None: # search everything + match = cre.search(incoming) + else: + startpos = max(0, len(incoming) - searchwindowsize) + match = cre.search(incoming, startpos) + if match is None: + continue + if first_match > match.start() or first_match == -1: + first_match = match.start() + self.match = match + self.match_index = pattern_list.index(cre) + if first_match > -1: + self.buffer = incoming[self.match.end() : ] + self.before = incoming[ : self.match.start()] + self.after = incoming[self.match.start() : self.match.end()] + return self.match_index + # No match at this point + if timeout < 0 and timeout is not None: + raise TIMEOUT ('Timeout exceeded in expect_list().') + # Still have time left, so read more data + c = self.read_nonblocking (self.maxread, timeout) + incoming = incoming + c + if timeout is not None: + timeout = end_time - time.time() + except EOF, e: + self.buffer = '' + self.before = incoming + self.after = EOF + if EOF in pattern_list: + self.match = EOF + self.match_index = pattern_list.index(EOF) + return self.match_index + else: + self.match = None + self.match_index = None + raise EOF (str(e) + '\n' + str(self)) + except TIMEOUT, e: + self.before = incoming + self.after = TIMEOUT + if TIMEOUT in pattern_list: + self.match = TIMEOUT + self.match_index = pattern_list.index(TIMEOUT) + return self.match_index + else: + self.match = None + self.match_index = None + raise TIMEOUT (str(e) + '\n' + str(self)) + except Exception: + self.before = incoming + self.after = None + self.match = None + self.match_index = None + raise + + def getwinsize(self): + """This returns the window size of the child tty. + The return value is a tuple of (rows, cols). + """ + if 'TIOCGWINSZ' in dir(termios): + TIOCGWINSZ = termios.TIOCGWINSZ + else: + TIOCGWINSZ = 1074295912L # Assume + s = struct.pack('HHHH', 0, 0, 0, 0) + x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s) + return struct.unpack('HHHH', x)[0:2] + + def setwinsize(self, r, c): + """This sets the window size of the child tty. + This will cause a SIGWINCH signal to be sent to the child. + This does not change the physical window size. + It changes the size reported to TTY-aware applications like + vi or curses -- applications that respond to the SIGWINCH signal. + """ + # Check for buggy platforms. Some Python versions on some platforms + # (notably OSF1 Alpha and RedHat 7.1) truncate the value for + # termios.TIOCSWINSZ. It is not clear why this happens. + # These platforms don't seem to handle the signed int very well; + # yet other platforms like OpenBSD have a large negative value for + # TIOCSWINSZ and they don't have a truncate problem. + # Newer versions of Linux have totally different values for TIOCSWINSZ. + # Note that this fix is a hack. + if 'TIOCSWINSZ' in dir(termios): + TIOCSWINSZ = termios.TIOCSWINSZ + else: + TIOCSWINSZ = -2146929561 + if TIOCSWINSZ == 2148037735L: # L is not required in Python >= 2.2. + TIOCSWINSZ = -2146929561 # Same bits, but with sign. + # Note, assume ws_xpixel and ws_ypixel are zero. + s = struct.pack('HHHH', r, c, 0, 0) + fcntl.ioctl(self.fileno(), TIOCSWINSZ, s) + + def interact(self, escape_character = chr(29)): + """This gives control of the child process to the interactive user + (the human at the keyboard). + Keystrokes are sent to the child process, and the stdout and stderr + output of the child process is printed. + When the user types the escape_character this method will stop. + The default for escape_character is ^] (ASCII 29). + This simply echos the child stdout and child stderr to the real + stdout and it echos the real stdin to the child stdin. + + Note that if you change the window size of the parent + the SIGWINCH signal will not be passed through to the child. + If you want the child window size to change when the parent's + window size changes then do something like the following example: + import pexpect, struct, fcntl, termios, signal, sys + def sigwinch_passthrough (sig, data): + s = struct.pack("HHHH", 0, 0, 0, 0) + a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s)) + global p + p.setwinsize(a[0],a[1]) + p = pexpect.spawn('/bin/bash') # Note this is global + signal.signal(signal.SIGWINCH, sigwinch_passthrough) + p.interact() + """ + # Flush the buffer. + self.stdout.write (self.buffer) + self.stdout.flush() + self.buffer = '' + mode = tty.tcgetattr(self.STDIN_FILENO) + tty.setraw(self.STDIN_FILENO) + try: + self.__interact_copy(escape_character) + finally: + tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode) + + def __interact_writen(self, fd, data): + """This is used by the interact() method. + """ + while data != '' and self.isalive(): + n = os.write(fd, data) + data = data[n:] + def __interact_read(self, fd): + """This is used by the interact() method. + """ + return os.read(fd, 1000) + def __interact_copy(self, escape_character = None): + """This is used by the interact() method. + """ + while self.isalive(): + try: + r, w, e = select.select([self.child_fd, self.STDIN_FILENO], [], []) + except select.errno, e: + if e[0] != errno.EINTR: + raise + if self.child_fd in r: + data = self.__interact_read(self.child_fd) + if self.logfile != None: + self.logfile.write (data) + self.logfile.flush() + os.write(self.STDOUT_FILENO, data) + if self.STDIN_FILENO in r: + data = self.__interact_read(self.STDIN_FILENO) + self.__interact_writen(self.child_fd, data) + if escape_character in data: + break +############################################################################## +# The following methods are no longer supported or allowed.. + def setmaxread (self, maxread): + """This method is no longer supported or allowed. + I don't like getters and setters without a good reason. + """ + raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the maxread member variable.') + def expect_exact (self, pattern_list, timeout = -1): + """This method is no longer supported or allowed. + It was too hard to maintain and keep it up to date with expect_list. + Few people used this method. Most people favored reliability over speed. + The implementation is left in comments in case anyone needs to hack this + feature back into their copy. + If someone wants to diff this with expect_list and make them work + nearly the same then I will consider adding this make in. + """ + raise ExceptionPexpect ('This method is no longer supported or allowed.') + def setlog (self, fileobject): + """This method is no longer supported or allowed. + """ + raise ExceptionPexpect ('This method is no longer supported or allowed. Just assign a value to the logfile member variable.') + +############################################################################## +# End of spawn class +############################################################################## + +def which (filename): + """This takes a given filename; tries to find it in the environment path; + then checks if it is executable. + This returns the full path to the filename if found and executable. + Otherwise this returns None. + """ + # Special case where filename already contains a path. + if os.path.dirname(filename) != '': + if os.access (filename, os.X_OK): + return filename + + if not os.environ.has_key('PATH') or os.environ['PATH'] == '': + p = os.defpath + else: + p = os.environ['PATH'] + + # Oddly enough this was the one line that made Pexpect + # incompatible with Python 1.5.2. + #pathlist = p.split (os.pathsep) + pathlist = string.split (p, os.pathsep) + + for path in pathlist: + f = os.path.join(path, filename) + if os.access(f, os.X_OK): + return f + return None + +def split_command_line(command_line): + """This splits a command line into a list of arguments. + It splits arguments on spaces, but handles + embedded quotes, doublequotes, and escaped characters. + It's impossible to do this with a regular expression, so + I wrote a little state machine to parse the command line. + """ + arg_list = [] + arg = '' + + # Constants to name the states we can be in. + state_basic = 0 + state_esc = 1 + state_singlequote = 2 + state_doublequote = 3 + state_whitespace = 4 # The state of consuming whitespace between commands. + state = state_basic + + for c in command_line: + if state == state_basic or state == state_whitespace: + if c == '\\': # Escape the next character + state = state_esc + elif c == r"'": # Handle single quote + state = state_singlequote + elif c == r'"': # Handle double quote + state = state_doublequote + elif c.isspace(): + # Add arg to arg_list if we aren't in the middle of whitespace. + if state == state_whitespace: + None # Do nothing. + else: + arg_list.append(arg) + arg = '' + state = state_whitespace + else: + arg = arg + c + state = state_basic + elif state == state_esc: + arg = arg + c + state = state_basic + elif state == state_singlequote: + if c == r"'": + state = state_basic + else: + arg = arg + c + elif state == state_doublequote: + if c == r'"': + state = state_basic + else: + arg = arg + c + + if arg != '': + arg_list.append(arg) + return arg_list + diff -r 1bcc0070c2f6 -r 226c97efb693 tools/python-PE/graffleConfig/FederatedLinda.pyc Binary file tools/python-PE/graffleConfig/FederatedLinda.pyc has changed diff -r 1bcc0070c2f6 -r 226c97efb693 tools/python-PE/graffleConfig/PListReader.pyc Binary file tools/python-PE/graffleConfig/PListReader.pyc has changed diff -r 1bcc0070c2f6 -r 226c97efb693 tools/python-PE/graffleConfig/W3CDate.pyc Binary file tools/python-PE/graffleConfig/W3CDate.pyc has changed