changeset 83:226c97efb693 fuchita

merge
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Sun, 20 Dec 2009 11:44:21 +0900
parents 1bcc0070c2f6 (current diff) dce00142f374 (diff)
children a1d796c0e975
files src/fdl/ByteBufferReader.java src/fdl/ComDebug.java src/fdl/ComDebug_Client.java src/fdl/Handler.java src/fdl/IOParam.java src/fdl/PSXQueueInterface.java src/fdl/TestEtc.java src/fdl/TestPSXLinda.java
diffstat 150 files changed, 8767 insertions(+), 1791 deletions(-) [+]
line wrap: on
line diff
--- a/.classpath	Sat Feb 16 13:18:02 2008 +0900
+++ b/.classpath	Sun Dec 20 11:44:21 2009 +0900
@@ -2,5 +2,6 @@
 <classpath>
 	<classpathentry kind="src" path="src"/>
 	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
 	<classpathentry kind="output" path="bin"/>
 </classpath>
--- /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
+
+
--- /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
--- a/.project	Sat Feb 16 13:18:02 2008 +0900
+++ b/.project	Sun Dec 20 11:44:21 2009 +0900
@@ -1,11 +1,16 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <projectDescription>
-	<name>FederatedLinda-Java</name>
+	<name>FederatedLinda</name>
 	<comment></comment>
 	<projects>
 	</projects>
 	<buildSpec>
 		<buildCommand>
+			<name>org.python.pydev.PyDevBuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
 			<name>org.eclipse.jdt.core.javabuilder</name>
 			<arguments>
 			</arguments>
@@ -13,5 +18,6 @@
 	</buildSpec>
 	<natures>
 		<nature>org.eclipse.jdt.core.javanature</nature>
+		<nature>org.python.pydev.pythonNature</nature>
 	</natures>
 </projectDescription>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/.pydevproject	Sun Dec 20 11:44:21 2009 +0900
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?eclipse-pydev version="1.0"?>
+
+<pydev_project>
+<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.5</pydev_property>
+</pydev_project>
--- /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
--- /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 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<project name="FDL" default="jar"  basedir=".">
+
+  <!-- ****プロパティ**** -->
+  <!-- ソースファイルãŒã‚るディレクトリ -->
+  <property name="src" value="src"/>
+
+  <!-- クラスファイルを出力ã™ã‚‹ãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒª -->
+  <property name="classes" value="classes"/>
+
+  <!-- javadocを出力ã™ã‚‹ãƒ‡ã‚£ãƒ¬ã‚¯ãƒˆãƒª -->
+  <property name="javadoc" value="docs"/>
+
+  <!-- jarファイルå -->
+  <property name="jar" value="FedLinda.jar"/>
+
+  <!-- ****ターゲット**** -->
+  <!-- jarファイルã®ä½œæˆ -->
+  <target name="jar" depends="compile">
+    <jar jarfile="${jar}" basedir="${classes}"></jar>
+  </target>
+
+
+  <!-- コンパイル -->
+  <target name="compile">
+    <mkdir dir="${classes}" />
+    <javac encoding="UTF-8" srcdir="src" destdir="${classes}" fork="yes">
+        <compilerarg value="-J-Dfile.encoding=UTF8"/>
+        <sourcepath>
+         <pathelement path="src"/>
+        </sourcepath>
+    </javac>
+  </target>
+
+  <!-- javadocã®ä½œæˆ -->
+  <target name="javadoc">
+    <javadoc destdir="${javadoc}">
+      <fileset dir="${src}"/>
+    </javadoc>
+  </target>
+ 
+  <!-- 生æˆã—ãŸãƒ•ã‚¡ã‚¤ãƒ«ã‚„フォルダã®å‰Šé™¤ -->
+  <target name="clean">
+    <delete dir="${classes}" />
+    <delete dir="${javadoc}" />
+    <delete file="${jar}" />
+  </target>
+
+</project>
+
Binary file document/cls.graffle has changed
Binary file document/connect.graffle has changed
Binary file document/graphRing.png has changed
Binary file document/metaRing.xls has changed
Binary file document/meta_ring_three.graffle has changed
Binary file document/metaengine.graffle has changed
Binary file document/objring.xls has changed
--- /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
--- /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
--- /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
--- /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
Binary file document/ring_three.graffle has changed
Binary file document/uml.graffle has changed
--- /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
+
+
+
+
--- /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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <arpa/inet.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+
+#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);
+}
+
+
--- /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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <pthread.h>
+#include <arpa/inet.h>
+
+#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<len) {
+				count += fwrite(data+count, 1, len-count, out);
+			}
+			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);
+
+	mainLoop(tspace, 10, stdout);
+
+	//printf("mainLoop finished\n");
+	exit(EXIT_SUCCESS);
+}
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/examples/filesend/writer.c	Sun Dec 20 11:44:21 2009 +0900
@@ -0,0 +1,83 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <arpa/inet.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+
+#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 */
--- /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
--- /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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <pthread.h>
+#include <arpa/inet.h>
+
+#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);
+}
+
+
--- /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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <pthread.h>
+#include <arpa/inet.h>
+
+#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);
+}
+
+
--- /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
--- /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
--- /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
--- /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 <base_port> <ldserv_number>' % sys.argv[0]
+        sys.exit(1)
+
+    main(int(sys.argv[1]), int(sys.argv[2]))
Binary file scripts-java/pexpect.pyc has changed
--- 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<Integer, Tuple> 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));
 	}
+
 }
--- 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<len;i++) {
-			cbuf[i]=_buf.getChar();
-		}
-		return len;
-	}
-	
-	@Override
-	public void reset() {
-		_buf.reset();
-	}
-	
-	@Override
-	public void close() throws IOException {
-		// TODO Auto-generated method stub
-		
-	}
-
-}
--- a/src/fdl/ComDebug.java	Sat Feb 16 13:18:02 2008 +0900
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,131 +0,0 @@
-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.channels.SelectionKey;
-import java.nio.channels.SocketChannel;
-import java.util.Hashtable;
-import java.util.Iterator;
-import java.util.LinkedList;
-
-
-public class ComDebug implements PSXQueueInterface{
-	static final boolean debug = true;
-	//public static int seq = 0;
-	public static Hashtable<String, Integer> Com_Hashtable  = new Hashtable<String, Integer>();  
-	public static LinkedList<SocketChannel> Report_Channellist = new LinkedList<SocketChannel>();
-	
-	ComDebug(){
-		
-	}
-
-	public static void Report(LinkedList<SocketChannel> 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<report_txt.length();i++) {
-			data.putChar(report_txt.charAt(i));
-		}
-    	data.flip();    // limit = current position, position = 0
-    	
-		//commandをセット
-    	command.order(ByteOrder.BIG_ENDIAN);
-    	command.putInt(LINDA_PACKET_LENGTH_OFFSET,(report_txt).length()*2+LINDA_HEADER_SIZE-INT_SIZE);
-    	command.put(LINDA_MODE_OFFSET,(byte)'D');
-    	command.putShort(LINDA_ID_OFFSET,(short) 0);
-    	command.putInt(LINDA_SEQ_OFFSET,0);
-    	command.putInt(LINDA_DATA_LENGTH_OFFSET,(report_txt).length()*2);
-    	command.rewind();
-
-		//é€ä¿¡
-    	IOParam io = new IOParam();
-		Iterator <SocketChannel> 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<String, Integer> 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<SocketChannel> reportCh_list) {
-		SocketChannel repch = (SocketChannel) key.channel();
-		reportCh_list.add(repch);
-	}
-	
-	public static void delChannel(SelectionKey key, LinkedList<SocketChannel> reportCh_list) {
-		SocketChannel repch = (SocketChannel) key.channel();
-		reportCh_list.remove(repch);
-	}
-
-	
-	public void reportCh_remove(SelectionKey key, LinkedList<SocketChannel> 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);
-		}
-	}
-	
-}
--- 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<args.length; ++i) {
-				if("-h".equals(args[i])) {
-					host = (String)(args[++i]);
-					System.err.println("host = "+host);
-				} else {
-					//System.err.println(usages);
-				}
-				if("-p".equals(args[i])) {
-					port = Integer.parseInt(args[++i]);
-					System.err.println("port = "+port);
-				} else {
-					//System.err.println(usages);
-				}
-			}
-		} catch (NumberFormatException e) {
-			e.printStackTrace();
-		}
-		
-		
-		try {
-			PSXReply r;
-		    fdl = FederatedLinda.init();
-		    psx = fdl.open(host,port);
-		    r = psx.in(65535);
-			fdl.sync(1);
-			if(debug == true){
-			    System.out.println("PSXReply =>"+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;
-		}
-	}
-}
--- /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<String> logs = new LinkedList<String>();
+	// 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);
+	}
+
+}
--- 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<args.length; ++i) {
 				if("-p".equals(args[i])) {
 					port = Integer.parseInt(args[++i]);					
-				} else {
-					System.err.println(usages);
-				}
+				} 
 			}
 		} catch (NumberFormatException e) {
-			e.printStackTrace();
+			System.err.println(usages);
+			return;
+		}
+		try {
+			FDLindaServ serv;
+			serv = new FDLindaServ(port);
+			serv.mainLoop();
+		} catch (IOException e) {
+			System.err.println("Server Communiation Problem.");
+		}
+	}
+	
+	public void mainLoop() {
+		MetaLinda ml = new MetaLinda(tupleSpace, this);
+		me = new NullMetaEngine(ml);
+		//me = new MetaLogEngine(ml);
+		me.mainLoop();
+	}
+
+	public FDLindaServ(int port) throws IOException {
+		this.port = port;
+		//セレクタを生æˆ
+		selector = SelectorProvider.provider().openSelector();		
+		//ソケット・ãƒãƒ£ãƒãƒ«ã‚’生æˆãƒ»è¨­å®š
+		ssChannel = SelectorProvider.provider().openServerSocketChannel();
+		ssChannel.socket().setReuseAddress(true);
+		// this should work for IPv6/IPv4 dual stack
+		// check this using netstat -an result tcp46.
+		try {
+			InetSocketAddress address = new InetSocketAddress("::", port);
+			ssChannel.socket().bind(address);		
+		} catch (SocketException e) {
+			// for some bad IPv6 implementation
+			ssChannel.socket().bind(new InetSocketAddress(port));
 		}
-    	//セレクタを生æˆ
-		Selector selector = SelectorProvider.provider().openSelector();		
-        try {        	
-        	//ソケット・ãƒãƒ£ãƒãƒ«ã‚’生æˆãƒ»è¨­å®š
-        	ServerSocketChannel ssChannel = SelectorProvider.provider().openServerSocketChannel();
-        	InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), port);
-        	//ssChannel.socket().bind(new InetSocketAddress(port));
-        	ssChannel.socket().bind(address);
-        	ssChannel.configureBlocking(false);
-        	//ssChannel.socket().setReuseAddress(true);
-        	System.out.println("Server: litening at "+ssChannel);
-        	//セレクタã«ãƒãƒ£ãƒ³ãƒãƒ«ã‚’登録
-        	//ssChannel.register(selector, SelectionKey.OP_ACCEPT, new AcceptHandler(tuple_space));
-            //ssChannel.register(selector, ssChannel.validOps(), new AcceptHandler(tuple_space));
-            ssChannel.register(selector, SelectionKey.OP_ACCEPT, new AcceptHandler(tuple_space));
- 
-        	// セレクタã«ã‚ˆã‚‹ç›£è¦–    
-        	while (selector.keys().size() > 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<SelectionKey> 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);
 	}
 }
--- 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<Integer,PSXReply> seqHash;
 
-    public PSXQueue q_top,q_end;
-    public PSXReply r_top,r_end;
-    public Hashtable<Integer,PSXReply> 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<Integer, PSXReply>();
 	}
-	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<Integer, PSXReply>();
-    }
-
-    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<SelectionKey> 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<SelectionKey> 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;i<LINDA_HEADER_SIZE;i++) {
-    	    		System.out.println(command.get(i));
-    	    	}
-    	    	System.out.print("data:");
-    	    	for(int i=0;i<length;i++) {
-    	    		System.out.println(data.get(i));
-    	    	}
-    	    	data.rewind();
-    	    }***/
-    	    
-    	    int rseq = command.getInt(LINDA_SEQ_OFFSET);
-    	    int mode = command.get(LINDA_MODE_OFFSET);
-    	    Integer a;
-    	    /***
-    	    if (debug) {
-    	    	System.out.print("mode = ");
-    	    	System.out.println(mode);
-    	    	System.out.print("seq = ");
-    	    	System.out.println(rseq);
-    	    }***/
-    	    try {
-    	    	PSXReply r = seqHash.get((a = new Integer(rseq)));
-    		if (debug) {
-    			System.out.print("hash value = ");
-    			System.out.println(a.hashCode());
-    		}
-    		
-    		r.setAnswer(mode,command,data);
-
-    		if (r.callback != null ) {
-    		    r.callback.callback(data);
-    		}
-    	    } catch (NullPointerException e ) {
-    	    	if (debug) {
-    	    		System.out.println("hashed reply not found");
-    	    	}
-    		// can't happen
-    		return ;
-    	    }
-        }
+	public int sync() throws IOException {
+		return sync(0);
 	}
 
-	private void chkServe(SocketChannel sock) 
-				    throws IOException {
-	int length;
-	ByteBuffer command = ByteBuffer.allocate(LINDA_HEADER_SIZE);
-	command.order(ByteOrder.BIG_ENDIAN);
-
-	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);
-	    }
-
-	    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;i<LINDA_HEADER_SIZE;i++) {
-	    		System.out.println(command.get(i));
-	    	}
-	    	System.out.print("data:");
-	    	for(int i=0;i<length;i++) {
-	    		System.out.println(data.get(i));
-	    	}
-	    	data.rewind();
-	    }***/
-	    
-	    int rseq = command.getInt(LINDA_SEQ_OFFSET);
-	    int mode = command.get(LINDA_MODE_OFFSET);
-	    Integer a;
-	    /***
-	    if (debug) {
-	    	System.out.print("mode = ");
-	    	System.out.println(mode);
-	    	System.out.print("seq = ");
-	    	System.out.println(rseq);
-	    }***/
-	    try {
-	    	PSXReply r = seqHash.get((a = new Integer(rseq)));
-		if (debug) {
-			System.out.print("hash value = ");
-			System.out.println(a.hashCode());
+		try {
+			if (selector.select(mtimeout)>0) {
+		      for (Iterator<SelectionKey> it = selector.selectedKeys().iterator();it.hasNext(); ) {
+			        SelectionKey s = it.next();
+			        it.remove();
+			        try {
+			        	if (!s.isReadable()) 
+			        		throw new IOException();
+			        	TupleHandler handle = (TupleHandler)s.attachment();
+			        	handle.handle(s);
+			        } catch (IOException e) {
+			        	s.cancel();
+					log(Level.INFO,""+s.channel()+" is closed.");
+			        }
+		      }
+			}
+		} catch (IOException e) {
+			e.printStackTrace();
+		} catch (ClosedSelectorException e) {
+			// client should be know
 		}
-		
-		r.setAnswer(mode,command,data);
+
+		return key_num;
+	}
 
-		if (r.callback != null ) {
-		    r.callback.callback(data);
+	private void queueExec() {
+		while (q_top != null){
+			PSXQueue c = q_top;
+			c.send();
+			q_top = c.next;
+			qsize--;
 		}
-	    } catch (NullPointerException e ) {
-	    	if (debug) {
-	    		System.out.println("hashed reply not found");
-	    	}
-		// can't happen
-		return ;
-	    }
-    }
-    }
+	}
+	
+	PSXReply getReply(int rseq) {
+		Integer a;
+
+		PSXReply r = seqHash.get((a = new Integer(rseq)));
+		seqHash.remove(a);
+		return r;
+	}
+
+	public void log(Level level,String msg) {
+		System.err.println(msg);
+		if (level==Level.SEVERE)
+			new IOException().setStackTrace(null);
+	}
 }
 
 /* end */
--- a/src/fdl/Handler.java	Sat Feb 16 13:18:02 2008 +0900
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,9 +0,0 @@
-
-package fdl;
-import java.io.IOException;
-import java.nio.channels.ClosedChannelException;
-import java.nio.channels.SelectionKey;
-
-public interface Handler {
-    public void handle(SelectionKey key) throws ClosedChannelException, IOException;
-}
--- a/src/fdl/IOHandler.java	Sat Feb 16 13:18:02 2008 +0900
+++ b/src/fdl/IOHandler.java	Sun Dec 20 11:44:21 2009 +0900
@@ -6,177 +6,80 @@
 import java.nio.channels.ClosedChannelException;
 import java.nio.channels.SelectionKey;
 import java.nio.channels.SocketChannel;
-import java.util.Hashtable;
-import java.util.LinkedList;
-
+import java.util.logging.Level;
 
-public class IOHandler extends IOParam {
-    static final boolean debug = false;
-	public Tuple[] tuple_space;     
-	public ComDebug com_debug;
+public class IOHandler implements TupleHandler {
+    static final boolean debug = true;
+    public TupleSpace tupleSpace;
+    public SocketChannel ch;
+    public FDLindaServ fds;
 
-    public IOHandler(Tuple[] _tuple_space) {
-		super(_tuple_space);
-	}
+	String remoteString;
+	String localString;
+	public int cnt = 0;
     
-    public void handle(SelectionKey key)
-                    throws ClosedChannelException, IOException {        
-        // 書ãè¾¼ã¿å¯ã§ã‚ã‚Œã°ï¼Œèª­ã¿è¾¼ã¿ã‚’è¡Œã†
-        if (key.isReadable()) {
-            read(key);
-        }
+    public IOHandler(FDLindaServ fds, TupleSpace tupleSpace,SocketChannel ch) {
+    	this.tupleSpace = tupleSpace;
 
-        // 書ãè¾¼ã¿å¯ã§ã‚ã‚Œã°ï¼Œæ›¸ãè¾¼ã¿ã‚’è¡Œã†
-        /*if (key.isWritable() && key.isValid()) {
-            write(key);
-        }*/
+		remoteString = PSX.getRemoteHostAndPort(ch);
+		localString =  PSX.getLocalHostAndPort(ch);
+		this.ch = ch;
+		this.fds = fds;
     }
 
-    private void read(SelectionKey key)
-                    throws ClosedChannelException, IOException {
-        SocketChannel channel = (SocketChannel)key.channel();
-
-        // 読ã¿è¾¼ã¿ç”¨ã®ãƒãƒƒãƒ•ã‚¡ã®ç”Ÿæˆ
-        ByteBuffer command = ByteBuffer.allocate(LINDA_HEADER_SIZE);
-        command.order(ByteOrder.BIG_ENDIAN);
-        command.clear();
-        
-        int readsize = LINDA_HEADER_SIZE;
-        int count = 0;
-        
-        // 読ã¿è¾¼ã¿
-        while(readsize>0) {
-        	if(debug){
-        		System.out.print("reading command...");
-        	}
-        	count = channel.read(command);
-
-        	if(count < 0) {        		
-        		LinkedList<SocketChannel> 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<String, Integer> com_Loggingtable = ComDebug.Com_Hashtable;
-	    LinkedList<SocketChannel> 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<SocketChannel> 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();
 	}
+	
 }
--- /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);
+}
--- 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
--- /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
--- /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<MetaReply> replies=new LinkedList<MetaReply>();
+
+	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 */
--- /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();
+	}
+}
--- /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;
+	}
+
+}
--- /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) {
+	}
+
+
+}
--- /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();
+	}
+}
--- /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;i<log.length();i++) {
+			blog.putChar(log.charAt(i));
+		}
+		blog.flip();
+		return blog;
+	}
+
+	public static String getdataString(ByteBuffer data) {
+		String sendtext;
+		//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) {
+		}
+		cb.rewind();
+		data.rewind();
+	
+		sendtext = cb.toString();
+		return sendtext;
+	}
+
+	public static void send(SocketChannel ch, ByteBuffer command, ByteBuffer data) {
+		// if datalen in the header is different from ByteBuffer remaining(), we lost
+		// protocol synchronization. Make sure to have correct length now.
+		if (true) { 
+			int datalen = data==null?0:(data.limit()-data.position());
+//			if (command.getInt(LINDA_DATA_LENGTH_OFFSET)>0 && (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 */
--- 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 */
--- /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 */
--- 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 */
--- 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 */
--- 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;
+	}
 }
 
 
--- 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());		
-	}
-}
--- 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);
-    }
-}
-
--- 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;
-    }*/    
 }
--- 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;
 		
--- /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;
+	}
+
+
+}
--- 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;
 
 
 /**
--- /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. 
+ * <p>
+ * 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;
--- /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<String> hosts = new LinkedList<String>();
+	LinkedList<Integer> ports = new LinkedList<Integer>();
+	LinkedList<PSXLinda> psxs = new LinkedList<PSXLinda>();
+
+	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<args.length; ++i) {
+				if("-h".equals(args[i])) {
+					hosts.add(args[++i]);
+					System.err.println("host = "+hosts.getLast());
+				} else if("-p".equals(args[i])) {
+					ports.add(Integer.parseInt(args[++i]));
+					System.err.println("port = "+ports.getLast());
+				} else {
+					System.err.println(usages); return;
+				}
+			}
+			if (hosts.size()!=ports.size()) {
+				System.err.println("-h and -p pairs are always necessary.");
+				System.exit(1);
+			}
+		} catch (NumberFormatException e) {
+			e.printStackTrace();
+		}
+
+
+		try {
+			fdl = FederatedLinda.init();
+			for(int i=0;i<hosts.size();i++) {
+				String host = hosts.get(i);
+				int port = ports.get(i);
+
+				psx = fdl.open(host,port);
+				psxs.add(psx);
+				PSXCallback checkid = new PSXCallback() {
+					public void callback(ByteBuffer reply) {
+						int p = psxs.indexOf(psx);
+						System.out.println("PSXReply("+p+") =>"+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;
+		}
+	}
+}
--- /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());		
+	}
+}
--- /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();
+	}
+	
+
+}
--- /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.");
+		}
+	}
+
+
+}
+
--- /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) {
+		}
+	}
+	
+
+}
--- /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);
+	}
+}
+
--- /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();
+	}
+
+}
--- /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);
+	}
+
+	
+}
+
--- /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");
+		}
+
+	}
+
+}
--- /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();
+	}
+
+}
--- /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);
+	}
+
+}
+
--- /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
--- /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");
+
+	}
+	
+}
--- /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);
+	}
+}
--- /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;
+	}
+}
+
--- /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);
+	}
+
+}
+
--- /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
--- /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");
+
+	}
+	
+}
--- /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);
+	}
+}
--- /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();
+		}
+	}
+	
+}
--- /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<PSXLinda> 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<PSXLinda>();
+	}
+
+	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);
+	}
+
+}
--- /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<NodeManager> waitingNodes;
+	private ArrayList<NodeManager> waitedNodes;
+//	private ArrayList<NodeManager> sendNodes;
+
+	public NodeManager(MetaLinda ml, int port, int manageId) {
+		this.port = port;
+		this.manageId = manageId;
+		this.mLinda = ml;
+		hostName = null;
+		waitingNodes = new ArrayList<NodeManager>();
+		waitedNodes = new ArrayList<NodeManager>();
+//		sendNodes = new ArrayList<NodeManager>();
+	}
+	
+	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;
+	}
+	
+}
--- /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();
+		}
+	}
+	
+}
--- /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");
+	}
+	
+}
--- /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();
+		}
+	}
+	
+}
--- /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();
+			}
+		}
+	}
+
+}
--- /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();
+		}
+	}
+}
--- /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);
+	}
+
+}
--- /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();
+		}
+		
+	}
+
+}
--- /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
--- /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);
+		}
+		
+	}
+	
+}
--- /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);
+	}
+}
--- /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<args.length; ++k) {
+			if("-bufsize".equals(args[k])){
+				bufstring = args[++k];
+			} else if("-ring".equals(args[k])){
+				txt = args[++k];
+				ring = Integer.valueOf(txt);
+			} else {
+				System.err.println("引数指定ã®èª¤ã‚Šï¼šæœªçŸ¥ã®å¼•æ•°ãŒæŒ‡å®šã•ã‚Œã¾ã—ãŸ");
+            }
+		}
+		bufsize = Integer.parseInt(bufstring);
+		try {
+			chkhost();
+			FDLServWithSendMeta serv = new FDLServWithSendMeta(localport);
+			serv.mainLoop();
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+	
+	private static void chkhost() throws UnknownHostException{
+		String localhost = null;
+		BufferedReader br = null;
+		String hostTable[] = new String[ring+1];
+		try {
+			br = new BufferedReader(new FileReader("nodelist"));
+			int i = 0;
+			while (br.ready()) {
+				String line = br.readLine();
+				hostTable[i] = line;
+				i++;
+			}
+			localhost = InetAddress.getLocalHost().getHostName();
+			for (int j=0; j<hostTable.length; j++) {
+				if(localhost.equals(hostTable[j])){
+					nextHost = hostTable[++j];
+					if(j == ring) {
+						nextHost = hostTable[0];
+					}
+				}
+			}
+			
+			if(localhost.equals(hostTable[0])) {
+				chknum = 1;
+			}
+				
+			System.out.println("localhost:"+localhost);
+			System.out.println("nexthost:"+nextHost);
+		
+		} catch (FileNotFoundException e) {
+			e.printStackTrace();
+		} catch (IOException e){
+			e.printStackTrace();
+		}
+	}
+	
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/fdl/test/transfer/cluster/HostCheck.java	Sun Dec 20 11:44:21 2009 +0900
@@ -0,0 +1,64 @@
+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;
+
+public class HostCheck {
+	private static String bufstring;
+	private static String txt;
+	private static Integer ring;
+	private static int bufsize;
+	private static String nextHost;
+	private static int chknum;
+
+	public static void main(String[] args) {
+		String localhost = null;
+		BufferedReader br = null;
+		for (int k=0; k<args.length; ++k) {
+			if("-bufsize".equals(args[k])){
+				bufstring = args[++k];
+			} else if("-ring".equals(args[k])){
+				txt = args[++k];
+				ring = Integer.valueOf(txt);
+			} else {
+	        System.err.println("引数指定ã®èª¤ã‚Šï¼šæœªçŸ¥ã®å¼•æ•°ãŒæŒ‡å®šã•ã‚Œã¾ã—ãŸ");
+            }
+		}
+		String hostTable[] = new String[ring+1];
+		bufsize = Integer.parseInt(bufstring);
+		try {
+			br = new BufferedReader(new FileReader("nodelist"));
+			int i = 0;
+			while (br.ready()) {
+				String line = br.readLine();
+				hostTable[i] = line;
+				i++;
+			}
+			localhost = InetAddress.getLocalHost().getHostName();
+			for (int j=0; j<hostTable.length; j++){
+				if(localhost.equals(hostTable[j])){
+				nextHost = hostTable[++j];
+				if(j == ring) {
+					nextHost = hostTable[0];
+				}
+			}
+			}
+			if(localhost.equals(hostTable[0])) {
+				chknum = 1;
+			}
+			
+			System.out.println("localhost:"+localhost);
+			System.out.println("nexthost:"+nextHost);
+
+		} catch (FileNotFoundException e) {
+			e.printStackTrace();
+		} catch (IOException e){
+			e.printStackTrace();
+		}
+		ProtocolEngine pe = new ProtocolEngine(localhost, nextHost,chknum, bufsize, txt);
+		pe.start();
+	}
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/fdl/test/transfer/cluster/MetaProtocolEngine.java	Sun Dec 20 11:44:21 2009 +0900
@@ -0,0 +1,177 @@
+package fdl.test.transfer.cluster;
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import fdl.MetaEngine;
+import fdl.MetaLinda;
+import fdl.PSXLinda;
+import fdl.PSXReply;
+
+public class MetaProtocolEngine implements MetaEngine {
+	private int id = 10;
+
+	private PSXLinda psxget;
+	MetaLinda fdlmeta;
+	String host;
+	int port = 10000;
+	private PSXLinda psxsend;
+	private int chknum;
+
+	SimpleDateFormat DF = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
+
+	private int bufsize;
+
+	private String time;
+	private long timelong;
+	private String start;
+	private String txt;
+	private String transfer;
+	private long transferlong;
+
+	public MetaProtocolEngine(MetaLinda ml, String host, int chknum, int bufsize, String txt) {
+		this.host = host;
+		this.fdlmeta = ml;
+		this.chknum = chknum;
+		this.bufsize = bufsize;
+		this.txt = txt;
+	}
+
+	public void mainLoop(){
+		psxget = fdlmeta;
+		if (chknum == 1) {
+			try {
+				sendData();
+				start = DF.format(new Date());
+				System.out.println("Start Time => "+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();
+	}
+}
+
--- /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();
+		}
+		
+	}
+
+}
--- /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<args.length; ++i) {
+			if("-get".equals(args[i])){
+				getHost = args[++i];
+			} else if("-send".equals(args[i])){
+				sendHost = args[++i];
+			} else {
+	        System.err.println("引数指定ã®èª¤ã‚Šï¼šæœªçŸ¥ã®å¼•æ•°ãŒæŒ‡å®šã•ã‚Œã¾ã—ãŸ");
+            }
+		}
+		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ã«ãƒ‡ãƒ¼ã‚¿ã‚’é€ä¿¡ã™ã‚‹ã€‚
+//			ByteBuffer send = ByteBuffer.allocate(10);
+//			send.putInt(12);
+//			send.flip();
+//			getpsx.out(id , send);
+//			fdl.sync(1);
+//			System.out.println("Send Data");
+			// psxã«ãƒ‡ãƒ¼ã‚¿ã‚’用æ„
+			boolean running = true;
+			ByteBuffer data2 = ByteBuffer.allocate(10);
+			PSXReply in = getpsx.in(id);
+			while (running) {
+				if(in.ready()){
+					//psx1ã«ãƒ‡ãƒ¼ã‚¿ã‚’書ã出ã—
+					data2 = in.getData();
+					sendpsx.out(id,data2);
+					int i = data2.getInt();
+					data2.rewind();
+					System.out.println("transfer Data => "+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();
+		}
+	}
+
+}
--- /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
--- /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
--- /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) {
+			}
+		}
+		}
+}
--- /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) {
+			}
+		}
+		}
+	}
+
+	
+}
--- /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);
+	}
+	
+
+}
--- /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
--- /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();
+		}
+	}
+	
+}
--- /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) {
+			}
+		}
+		}
+	}
+	
+}
--- /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;
+	}
+}
--- /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();
+		}
+		
+	}
+
+}
--- /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
--- /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) {
+			}
+		}
+		}
+}
--- /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) {
+			}
+		}
+		}
+	}
+
+	
+}
--- /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);
+	}
+}
--- /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() ãŒå®Ÿè¡Œã•ã‚Œã‚‹");
+
+
+	}
+}
+
--- /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
--- /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);
+	        }
+	    }
+
+}
--- /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.");
+		}
+	
+	}
+}
--- /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();
+	}
+
+}
--- /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
--- 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
Binary file tools/Linda_library/liblindaapi.a has changed
--- 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 <stdio.h>
 #include <string.h>
@@ -11,13 +11,15 @@
 #include <unistd.h>
 #include <netinet/in.h>
 #include <sys/select.h>
-#include <sys/types.h>
-#include <sys/socket.h>
 #include <netdb.h>
 #include <netinet/tcp.h>
 #include <sys/un.h>
 #include <errno.h>
 
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+
 #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 - buf¤Îbyte¿ô
-  ÊÖ¤êÃÍ:
-      Á÷¤Ã¤¿(½ñ¤­¤³¤ó¤À)¥Ç¡¼¥¿¤Î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_queueÆâ¤Çmalloc¤µ¤ì¤¿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 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)¤¬Ê֤롣
+  引ãæ•°:
+      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<pkt;a+=i) {
@@ -649,16 +664,16 @@
 /*-------------------------------------------------------------------/
   static unsigned int
   get_int(unsigned char * tuple, int offset):
-      TUPLE¤Î¥Ø¥Ã¥À¤Ë³ÊǼ¤µ¤ì¤¿ int·¿ ¤Î¥Ç¡¼¥¿¤òÆÀ¤ë¤¿¤á¤Î´Ø¿ô
-      psx_get_datalength() ¤È psx_get_seq() ¤«¤é¸Æ¤Ð¤ì¤ë¡£
+      TUPLEã®ãƒ˜ãƒƒãƒ€ã«æ ¼ç´ã•ã‚ŒãŸ intåž‹ ã®ãƒ‡ãƒ¼ã‚¿ã‚’å¾—ã‚‹ãŸã‚ã®é–¢æ•°
+      psx_get_datalength() 㨠psx_get_seq() ã‹ã‚‰å‘¼ã°ã‚Œã‚‹ã€‚
 
-  °ú¤­¿ô:
-      tuple  - ¥Ø¥Ã¥À¾ðÊó¤â´Þ¤ó¤ÀTUPLE¡£psx_reply()¤ÇÆÀ¤¿¤â¤Î¤Ç¤â¤¤¤¤¡£
-      offset - ¼è¤ê¤À¤¹¥Ç¡¼¥¿¤Î¥ª¥Õ¥»¥Ã¥È¡£LINDA_DATA_LENGTH_OFFSET
-               ¤« LINDA_SEQ_OFFSET¡£
+  引ãæ•°:
+      tuple  - ヘッダ情報もå«ã‚“ã TUPLE。psx_reply()ã§å¾—ãŸã‚‚ã®ã§ã‚‚ã„ã„。
+      offset - å–ã‚Šã ã™ãƒ‡ãƒ¼ã‚¿ã®ã‚ªãƒ•ã‚»ãƒƒãƒˆã€‚LINDA_DATA_LENGTH_OFFSET
+               ㋠LINDA_SEQ_OFFSET。
 
-  ÊÖ¤êÃÍ:
-      »ØÄꤷ¤¿¥ª¥Õ¥»¥Ã¥È¤Ë³ÊǼ¤µ¤ì¤Æ¤¤¤¿¿ôÃÍ(int·¿)
+  返り値:
+      指定ã—ãŸã‚ªãƒ•ã‚»ãƒƒãƒˆã«æ ¼ç´ã•ã‚Œã¦ã„ãŸæ•°å€¤(intåž‹)
 /-------------------------------------------------------------------*/
 static unsigned int
 get_int(unsigned char * tuple, int offset){
--- a/tools/Linda_library/lindaapi.h	Sat Feb 16 13:18:02 2008 +0900
+++ b/tools/Linda_library/lindaapi.h	Sun Dec 20 11:44:21 2009 +0900
@@ -1,7 +1,7 @@
 /*  $Id$ */
 
 /*----------------------------------------------------------------------
-  ¥Þ¥¯¥íÄêµÁ
+  マクロ定義
 ----------------------------------------------------------------------*/
 
 #define FAIL            (-1)
@@ -15,7 +15,7 @@
 #define LDSERV_PORT     11511
 
 /*----------------------------------------------------------------------
- ¥Ñ¥±¥Ã¥È¥Õ¥©¡¼¥Þ¥Ã¥È
+ パケットフォーマット
  char     short  int    int
  Mode +   ID   + Seq  + Data_len + Padding + Data
  0        1      3      7          11        12
@@ -28,7 +28,7 @@
 #define LINDA_HEADER_SIZE          12
 
 /*----------------------------------------------------------------------
-  ¹½Â¤ÂÎÄêµÁ
+  構造体定義
 ----------------------------------------------------------------------*/
 typedef struct psx_reply{
     unsigned char *answer;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/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 <base_port> <ldserv_number>' % sys.argv[0]
+        sys.exit(1)
+
+    main(int(sys.argv[1]), int(sys.argv[2]))
--- /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 ".*<processname>.*" 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 <process_name>" % sys.argv[0]
+        sys.exit(1)
+
+    main(sys.argv[1])
+
--- /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 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>java3d-test</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+	</buildSpec>
+	<natures>
+	</natures>
+</projectDescription>
--- /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
--- /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<String, String> map){
+		for (String str : map.keySet()){
+			System.out.println(str + ": " + map.get(str));
+		}
+	}
+	
+	public static void main(String[] args){
+		//HashMapã®ã‚¤ãƒ³ã‚¹ã‚¿ãƒ³ã‚¹åŒ–
+		Map <String,String> map = new HashMap<String,String>();
+		
+		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);
+		
+		
+	}
+	
+}
--- /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
--- /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 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<アラン 演技力="10" 歌唱力="8" スター性="2" 勘é•ã„="10" 特殊能力="10"></アラン>
\ No newline at end of file
--- /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
--- /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();
+        }
+    }
+}
--- /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;
+
+/*
+    <applet code=Java3DProgram width=200 height=200>
+    </applet>
+*/
+
+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
--- /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<String, Object> map = new HashMap<String, Object>();
+	
+	public void addinteger(String name, String i){
+		map.put(name, i);
+	}
+
+}
--- /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);
+        }
+}
+
--- /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);
+    }
+}
--- /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<tab;i++){
+	    System.out.print("\t");
+	}
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/java3d-test/src/SaxSample.java	Sun Dec 20 11:44:21 2009 +0900
@@ -0,0 +1,22 @@
+import java.io.*;
+import javax.xml.parsers.*;
+
+class SaxSample{
+    public static void main(String args[]){
+	try{
+	    /*パーサã®Factoryを作æˆ
+	      åå‰ã‹ã‚‰ã—ã¦Factoryパターンã§,Singletonã ã¨æ€ã†.*/
+	    SAXParserFactory spf=SAXParserFactory.newInstance();
+	    /*パーサをå–å¾—*/
+	    SAXParser sp=spf.newSAXParser();
+	    
+	    /*イベントãƒãƒ³ãƒ‰ãƒ©ã‚’作æˆ*/
+	    SampleHandler sh=new SampleHandler();
+
+	    /*イベントãƒãƒ³ãƒ‰ãƒ©ã«å…¥åŠ›ãƒ‡ãƒ¼ã‚¿ã¨ã‚¤ãƒ™ãƒ³ãƒˆãƒãƒ³ãƒ‰ãƒ©ã‚’渡ã™*/
+	    sp.parse(new FileInputStream("src/example.graffle"),sh);
+	}catch(Exception e){
+	    e.printStackTrace();
+	}
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/java3d-test/src/audition.xml	Sun Dec 20 11:44:21 2009 +0900
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<casts>
+  <cast>
+  <name>アラン</name>
+    <play>four</play>
+    <song>8</song>
+    <star>2</star>
+    <mistake>10</mistake>
+    <special>10</special>
+  </cast>
+</casts>
--- /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 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>ActiveLayerIndex</key>
+	<integer>0</integer>
+	<key>AutoAdjust</key>
+	<false/>
+	<key>CanvasColor</key>
+	<dict>
+		<key>w</key>
+		<string>1</string>
+	</dict>
+	<key>CanvasOrigin</key>
+	<string>{0, 0}</string>
+	<key>CanvasScale</key>
+	<real>1</real>
+	<key>ColumnAlign</key>
+	<integer>1</integer>
+	<key>ColumnSpacing</key>
+	<real>36</real>
+	<key>CreationDate</key>
+	<string>2006-02-14 12:48:50 +0900</string>
+	<key>Creator</key>
+	<string>安æ‘æ­ä¸€</string>
+	<key>DisplayScale</key>
+	<string>1 cm = 1 cm</string>
+	<key>GraphDocumentVersion</key>
+	<integer>5</integer>
+	<key>GraphicsList</key>
+	<array>
+		<dict>
+			<key>Class</key>
+			<string>LineGraphic</string>
+			<key>Head</key>
+			<dict>
+				<key>ID</key>
+				<integer>11</integer>
+			</dict>
+			<key>ID</key>
+			<integer>25</integer>
+			<key>Points</key>
+			<array>
+				<string>{299, 125.5}</string>
+				<string>{299, 205.5}</string>
+			</array>
+			<key>Style</key>
+			<dict>
+				<key>stroke</key>
+				<dict>
+					<key>HeadArrow</key>
+					<string>0</string>
+					<key>TailArrow</key>
+					<string>0</string>
+				</dict>
+			</dict>
+			<key>Tail</key>
+			<dict>
+				<key>ID</key>
+				<integer>9</integer>
+			</dict>
+		</dict>
+		<dict>
+			<key>Class</key>
+			<string>LineGraphic</string>
+			<key>Head</key>
+			<dict>
+				<key>ID</key>
+				<integer>10</integer>
+			</dict>
+			<key>ID</key>
+			<integer>24</integer>
+			<key>Points</key>
+			<array>
+				<string>{277.767, 115.479}</string>
+				<string>{156.233, 215.521}</string>
+			</array>
+			<key>Style</key>
+			<dict>
+				<key>stroke</key>
+				<dict>
+					<key>HeadArrow</key>
+					<string>0</string>
+					<key>TailArrow</key>
+					<string>0</string>
+				</dict>
+			</dict>
+			<key>Tail</key>
+			<dict>
+				<key>ID</key>
+				<integer>9</integer>
+			</dict>
+		</dict>
+		<dict>
+			<key>Class</key>
+			<string>LineGraphic</string>
+			<key>Head</key>
+			<dict>
+				<key>ID</key>
+				<integer>9</integer>
+			</dict>
+			<key>ID</key>
+			<integer>23</integer>
+			<key>Points</key>
+			<array>
+				<string>{162.5, 98}</string>
+				<string>{271.5, 98}</string>
+			</array>
+			<key>Style</key>
+			<dict>
+				<key>stroke</key>
+				<dict>
+					<key>HeadArrow</key>
+					<string>0</string>
+					<key>TailArrow</key>
+					<string>0</string>
+				</dict>
+			</dict>
+			<key>Tail</key>
+			<dict>
+				<key>ID</key>
+				<integer>2</integer>
+			</dict>
+		</dict>
+		<dict>
+			<key>Bounds</key>
+			<string>{{272, 206}, {54, 54}}</string>
+			<key>Class</key>
+			<string>ShapedGraphic</string>
+			<key>ID</key>
+			<integer>11</integer>
+			<key>Shape</key>
+			<string>Circle</string>
+		</dict>
+		<dict>
+			<key>Bounds</key>
+			<string>{{108, 206}, {54, 54}}</string>
+			<key>Class</key>
+			<string>ShapedGraphic</string>
+			<key>ID</key>
+			<integer>10</integer>
+			<key>Shape</key>
+			<string>Circle</string>
+		</dict>
+		<dict>
+			<key>Bounds</key>
+			<string>{{272, 71}, {54, 54}}</string>
+			<key>Class</key>
+			<string>ShapedGraphic</string>
+			<key>ID</key>
+			<integer>9</integer>
+			<key>Shape</key>
+			<string>Circle</string>
+		</dict>
+		<dict>
+			<key>Bounds</key>
+			<string>{{108, 71}, {54, 54}}</string>
+			<key>Class</key>
+			<string>ShapedGraphic</string>
+			<key>ID</key>
+			<integer>2</integer>
+			<key>Shape</key>
+			<string>Circle</string>
+		</dict>
+	</array>
+	<key>GridInfo</key>
+	<dict>
+		<key>GridSpacing</key>
+		<real>14.17322826385498</real>
+		<key>MajorGridSpacing</key>
+		<integer>10</integer>
+	</dict>
+	<key>GuidesLocked</key>
+	<string>NO</string>
+	<key>GuidesVisible</key>
+	<string>YES</string>
+	<key>HPages</key>
+	<integer>1</integer>
+	<key>ImageCounter</key>
+	<integer>1</integer>
+	<key>IsPalette</key>
+	<string>NO</string>
+	<key>KeepToScale</key>
+	<false/>
+	<key>Layers</key>
+	<array>
+		<dict>
+			<key>Lock</key>
+			<string>NO</string>
+			<key>Name</key>
+			<string>Layer 1</string>
+			<key>Print</key>
+			<string>YES</string>
+			<key>View</key>
+			<string>YES</string>
+		</dict>
+	</array>
+	<key>LayoutInfo</key>
+	<dict>
+		<key>ChildOrdering</key>
+		<integer>0</integer>
+	</dict>
+	<key>LinksVisible</key>
+	<string>NO</string>
+	<key>MagnetsVisible</key>
+	<string>NO</string>
+	<key>MasterSheet</key>
+	<string>マスター 1</string>
+	<key>MasterSheets</key>
+	<array>
+		<dict>
+			<key>ActiveLayerIndex</key>
+			<integer>0</integer>
+			<key>AutoAdjust</key>
+			<false/>
+			<key>CanvasColor</key>
+			<dict>
+				<key>w</key>
+				<string>1</string>
+			</dict>
+			<key>CanvasOrigin</key>
+			<string>{0, 0}</string>
+			<key>CanvasScale</key>
+			<real>1</real>
+			<key>ColumnAlign</key>
+			<integer>1</integer>
+			<key>ColumnSpacing</key>
+			<real>36</real>
+			<key>DisplayScale</key>
+			<string>1 cm = 1 cm</string>
+			<key>GraphicsList</key>
+			<array/>
+			<key>GridInfo</key>
+			<dict>
+				<key>GridSpacing</key>
+				<real>14.17322826385498</real>
+				<key>MajorGridSpacing</key>
+				<integer>10</integer>
+			</dict>
+			<key>HPages</key>
+			<integer>1</integer>
+			<key>IsPalette</key>
+			<string>NO</string>
+			<key>KeepToScale</key>
+			<false/>
+			<key>Layers</key>
+			<array>
+				<dict>
+					<key>Lock</key>
+					<string>NO</string>
+					<key>Name</key>
+					<string>レイヤー 1</string>
+					<key>Print</key>
+					<string>YES</string>
+					<key>View</key>
+					<string>YES</string>
+				</dict>
+			</array>
+			<key>LayoutInfo</key>
+			<dict>
+				<key>ChildOrdering</key>
+				<integer>0</integer>
+			</dict>
+			<key>Orientation</key>
+			<integer>2</integer>
+			<key>RowAlign</key>
+			<integer>1</integer>
+			<key>RowSpacing</key>
+			<real>36</real>
+			<key>SheetTitle</key>
+			<string>マスター 1</string>
+			<key>UniqueID</key>
+			<integer>1</integer>
+			<key>VPages</key>
+			<integer>1</integer>
+		</dict>
+	</array>
+	<key>ModificationDate</key>
+	<string>2008-02-07 22:06:25 +0900</string>
+	<key>Modifier</key>
+	<string>Fuchita Yoshihiko</string>
+	<key>NotesVisible</key>
+	<string>NO</string>
+	<key>Orientation</key>
+	<integer>2</integer>
+	<key>OriginVisible</key>
+	<string>NO</string>
+	<key>PageBreaks</key>
+	<string>YES</string>
+	<key>PrintInfo</key>
+	<dict>
+		<key>NSBottomMargin</key>
+		<array>
+			<string>float</string>
+			<string>0</string>
+		</array>
+		<key>NSJobFeatures</key>
+		<array>
+			<string>coded</string>
+			<string>BAt0eXBlZHN0cmVhbYED6IQBQISEhBNOU011dGFibGVEaWN0aW9uYXJ5AISEDE5TRGljdGlvbmFyeQCEhAhOU09iamVjdACFhAFpAIY=</string>
+		</array>
+		<key>NSLeftMargin</key>
+		<array>
+			<string>float</string>
+			<string>0</string>
+		</array>
+		<key>NSPagesPerSheet</key>
+		<array>
+			<string>int</string>
+			<string>1</string>
+		</array>
+		<key>NSPaperSize</key>
+		<array>
+			<string>size</string>
+			<string>{595, 842}</string>
+		</array>
+		<key>NSPrintAllPages</key>
+		<array>
+			<string>int</string>
+			<string>0</string>
+		</array>
+		<key>NSReversePageOrder</key>
+		<array>
+			<string>int</string>
+			<string>0</string>
+		</array>
+		<key>NSRightMargin</key>
+		<array>
+			<string>float</string>
+			<string>0</string>
+		</array>
+		<key>NSTopMargin</key>
+		<array>
+			<string>float</string>
+			<string>0</string>
+		</array>
+	</dict>
+	<key>ReadOnly</key>
+	<string>NO</string>
+	<key>RowAlign</key>
+	<integer>1</integer>
+	<key>RowSpacing</key>
+	<real>36</real>
+	<key>SheetTitle</key>
+	<string>Canvas 1</string>
+	<key>SmartAlignmentGuidesActive</key>
+	<string>YES</string>
+	<key>SmartDistanceGuidesActive</key>
+	<string>YES</string>
+	<key>UniqueID</key>
+	<integer>1</integer>
+	<key>UseEntirePage</key>
+	<true/>
+	<key>VPages</key>
+	<integer>1</integer>
+	<key>WindowInfo</key>
+	<dict>
+		<key>CurrentSheet</key>
+		<string>0</string>
+		<key>DrawerOpen</key>
+		<false/>
+		<key>DrawerTab</key>
+		<string>Outline</string>
+		<key>DrawerWidth</key>
+		<real>209</real>
+		<key>FitInWindow</key>
+		<false/>
+		<key>Frame</key>
+		<string>{{324, 0}, {574, 800}}</string>
+		<key>ShowRuler</key>
+		<false/>
+		<key>ShowStatusBar</key>
+		<true/>
+		<key>VisibleRegion</key>
+		<string>{{0, 0}, {559, 686}}</string>
+		<key>Zoom</key>
+		<string>1</string>
+	</dict>
+</dict>
+</plist>
--- /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; i<n; i++){
+			float xi=xmin+i*xdelta;
+			float xii=xi+xdelta;
+			float xcenter=xi+0.5f*xdelta;
+			for(int j=0; j<n; j++){
+				int tmp=6*(i*n+j);
+				float yj=ymin+j*ydelta;
+				float yjj=yj+ydelta;
+				float ycenter=yj+0.5f*ydelta;
+
+				coord[tmp]=new Point3f(xn(xcenter),yn(ycenter),zn(zcenter[i][j]));
+				coord[tmp+1]=new Point3f(xn(xi),yn(yj),zn(zvalue[i][j]));
+				coord[tmp+2]=new Point3f(xn(xii),yn(yj),zn(zvalue[i+1][j]));
+				coord[tmp+3]=new Point3f(xn(xii),yn(yjj),zn(zvalue[i+1][j+1]));
+				coord[tmp+4]=new Point3f(xn(xi),yn(yjj),zn(zvalue[i][j+1]));
+				coord[tmp+5]=coord[tmp+1];
+				
+				color[tmp]=hcolor(zn(zcenter[i][j]));
+				color[tmp+1]=hcolor(zn(zvalue[i][j]));
+				color[tmp+2]=hcolor(zn(zvalue[i+1][j]));
+				color[tmp+3]=hcolor(zn(zvalue[i+1][j+1]));
+				color[tmp+4]=hcolor(zn(zvalue[i][j+1]));
+				color[tmp+5]=color[tmp+1];
+			}
+		}
+		
+		int stripCounts[] = new int[n*n];
+		for(int i=0; i<n*n; i++){stripCounts[i]=6;}
+		
+		TriangleFanArray tfa =
+			new TriangleFanArray(
+				totalN,
+				TriangleFanArray.COORDINATES|TriangleFanArray.COLOR_3,
+				stripCounts
+			);
+		tfa.setCoordinates(0,coord);
+		tfa.setColors(0,color);
+		
+		//construct appearence
+		TransparencyAttributes surftr;
+		if(addSurface){
+			surftr = new TransparencyAttributes(TransparencyAttributes.NONE,0.0f);
+		}else{
+			surftr = new TransparencyAttributes(TransparencyAttributes.NICEST,1.0f);
+		}
+		PolygonAttributes attr = new PolygonAttributes();
+		attr.setCullFace(PolygonAttributes.CULL_NONE);
+		attr.setPolygonMode(PolygonAttributes.POLYGON_FILL);
+
+		Appearance appear = new Appearance();
+		appear.setPolygonAttributes(attr);
+		appear.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_READ);
+		appear.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_WRITE);
+		appear.setTransparencyAttributes(surftr);
+
+		//construct Shape3D for surface graph
+		Shape3D graphshape=new Shape3D();
+		graphshape.removeGeometry(0);
+		graphshape.addGeometry(tfa);
+		graphshape.setAppearance(appear);
+		graphshape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE);
+		graphshape.setCapability(Shape3D.ALLOW_APPEARANCE_READ);
+
+		return graphshape;
+	}
+	
+	//color data corresponding to the height
+	private Color3f hcolor(float h){
+		float r,g,b;
+		h=h*2;
+		if(h>1){ 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<n; i++){
+			for(j=0; j<n; j++){
+				zcenter[i][j]=f(xmin+(i+0.5f)*xdelta, ymin+(j+0.5f)*ydelta);
+			}
+		}
+		
+		// if necessary, determine zmin and zmax automatically
+		if(zmin==0.0f && zmax==0.0f){
+			zmin=Float.POSITIVE_INFINITY; zmax=Float.NEGATIVE_INFINITY;
+			for(i=0; i<=n; i++){
+				for(j=0; j<=n; j++){
+					zmin=Math.min(zmin,zvalue[i][j]);
+					zmax=Math.max(zmax,zvalue[i][j]);
+				}
+			}
+			for(i=0; i<n; i++){
+				for(j=0; j<n; j++){
+					zmin=Math.min(zmin,zcenter[i][j]);
+					zmax=Math.max(zmax,zcenter[i][j]);
+				}
+			}
+		}
+		
+		zwidth=zmax-zmin;
+		z0=(zmax+zmin)/2;
+
+		/////////// main part ///////////
+		setLayout(new BorderLayout());
+	
+		GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
+
+		Canvas3D canvas = new Canvas3D(config);
+		add("Center", canvas);
+
+		SimpleUniverse universe = new SimpleUniverse(canvas);
+		universe.getViewingPlatform().setNominalViewingTransform();
+		
+		//construct graphic objects
+		surfaceGraph = graph();
+		meshGraph = meshgraph();
+		xyPlane = xyplane();
+		xyzAxes = axes();
+		xyzArrowHead = arrowhead();
+		xyzAxesLabels = axeslabels();
+
+		BranchGroup scene = createSceneGraph();
+		universe.addBranchGraph(scene);
+	}
+	
+	//main method to make both of Application and Applet	
+	public static void main(String[] args) {
+		Frame frame = new MainFrame(new graff3d(), 480, 480);
+    }
+
+/////////////////////////////////////////////////
+// define our function and give necessary data //
+/////////////////////////////////////////////////
+	
+	// our function
+	float f(float x, float y){
+		return x*x-y*y;
+		//return x*x*x + y*y*y - 3*x*y;
+		//return (y-x*x)*(y-2*x*x);
+		//return (float)Math.sin(x*x+y*y);
+		//if(x==0.0f){ return 0.0f; } else { return y*y/x; }
+		//if((x==0.0f) && (y==0.0f)){ return 0.5f; } else {return x*y/(x*x+y*y);}
+	}
+	
+	// domain of definition
+	float xmin=-1.0f;	// min of x
+	float xmax=1.0f;	// max of x
+	float ymin=-1.0f;	// min of y
+	float ymax=1.0f;	// max of y
+	
+	// range of the value
+	//     If both of zmin and zmax are set to 0.0f, then zmin and zmax
+	//     are calculated automatically.
+	float zmin=0.0f;	// min of z
+	float zmax=0.0f;	// max of z
+	
+	int n=20;		// number of divisions for surface graph
+	int nmesh=20;	// number of divisions for mesh graph
+	
+	float meshLineWidth=2.0f;	// width of lines in mesh graph
+	
+	boolean addSurface=true;	// FLAG : show/erase surface graph
+	boolean addMesh=true;		// FLAG : show/erase mesh graph
+	boolean addXYPlane=false;	// FLAG : show/erase xy-plane
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/java3d-test/src/obj_test.java	Sun Dec 20 11:44:21 2009 +0900
@@ -0,0 +1,65 @@
+import java.applet.Applet;
+import com.sun.j3d.utils.applet.MainFrame;
+import javax.media.j3d.*;
+
+import java.awt.BorderLayout;
+
+import java.awt.GraphicsConfiguration;
+import com.sun.j3d.utils.universe.*;
+import com.sun.j3d.utils.geometry.ColorCube;
+import javax.vecmath.*;
+
+
+public class obj_test extends Applet {
+	
+	public SimpleUniverse universe = null;
+	public Canvas3D canvas = null;
+	
+	public BranchGroup createObjects(){
+		BranchGroup root = new BranchGroup();
+
+		
+		Transform3D matrix1 = new Transform3D();
+		matrix1.setTranslation(new Vector3d(1.0, 0.0, 0.0));
+
+		TransformGroup transRoot = new TransformGroup(matrix1);
+
+		ColorCube cube2 = new ColorCube(0.2d);
+        transRoot.addChild(cube2);
+		root.addChild(transRoot);
+		
+
+		root.compile();
+		
+		return root;
+		
+	}
+
+	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();
+		
+		TransformGroup viewtrans = universe.getViewingPlatform().getViewPlatformTransform();
+
+		
+		
+		
+		// マウスã§ãã‚Šãã‚Šå‹•ã‹ã™ãŸã‚ã®å‡¦ç†
+//        setOrbitBehavior();
+		
+		universe.addBranchGraph(createObjects());
+	}
+
+    public static void main(String[] args) {
+        new MainFrame(new obj_test(), 600, 600);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tools/java3d-test/src/sample.xml	Sun Dec 20 11:44:21 2009 +0900
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<drinks>
+    <drink type="soft">
+        <name>Apple</name>
+        <taste>Good</taste>
+    </drink>
+
+    <drink type="alcohol">
+        <name>Beer</name>
+	<taste>Bitter</taste>
+    </drink>
+
+    <drink type="alcohol">
+        <name>Whiskey</name>
+    </drink>
+</drinks>
--- /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
--- /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){}
+
+
+}
--- /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);
+    }
+    
+}
+    
--- /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 <matt (*) corvil.com>
+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
+
Binary file tools/python-PE/graffleConfig/FederatedLinda.pyc has changed
Binary file tools/python-PE/graffleConfig/PListReader.pyc has changed
Binary file tools/python-PE/graffleConfig/W3CDate.pyc has changed